babylon.glTFLoader.ts 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739
  1. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2. module BABYLON.GLTF1 {
  3. /**
  4. * Tokenizer. Used for shaders compatibility
  5. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  6. */
  7. enum ETokenType {
  8. IDENTIFIER = 1,
  9. UNKNOWN = 2,
  10. END_OF_INPUT = 3
  11. }
  12. class Tokenizer {
  13. private _toParse: string;
  14. private _pos: number = 0;
  15. private _maxPos: number;
  16. public currentToken: ETokenType;
  17. public currentIdentifier: string;
  18. public currentString: string;
  19. public isLetterOrDigitPattern: RegExp = /^[a-zA-Z0-9]+$/;
  20. constructor(toParse: string) {
  21. this._toParse = toParse;
  22. this._maxPos = toParse.length;
  23. }
  24. public getNextToken(): ETokenType {
  25. if (this.isEnd()) return ETokenType.END_OF_INPUT;
  26. this.currentString = this.read();
  27. this.currentToken = ETokenType.UNKNOWN;
  28. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  29. this.currentToken = ETokenType.IDENTIFIER;
  30. this.currentIdentifier = this.currentString;
  31. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  32. this.currentIdentifier += this.currentString;
  33. this.forward();
  34. }
  35. }
  36. return this.currentToken;
  37. }
  38. public peek(): string {
  39. return this._toParse[this._pos];
  40. }
  41. public read(): string {
  42. return this._toParse[this._pos++];
  43. }
  44. public forward(): void {
  45. this._pos++;
  46. }
  47. public isEnd(): boolean {
  48. return this._pos >= this._maxPos;
  49. }
  50. }
  51. /**
  52. * Values
  53. */
  54. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  55. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  56. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  57. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  58. /**
  59. * Parse
  60. */
  61. var parseBuffers = (parsedBuffers: any, gltfRuntime: IGLTFRuntime) => {
  62. for (var buf in parsedBuffers) {
  63. var parsedBuffer = parsedBuffers[buf];
  64. gltfRuntime.buffers[buf] = parsedBuffer;
  65. gltfRuntime.buffersCount++;
  66. }
  67. };
  68. var parseShaders = (parsedShaders: any, gltfRuntime: IGLTFRuntime) => {
  69. for (var sha in parsedShaders) {
  70. var parsedShader = parsedShaders[sha];
  71. gltfRuntime.shaders[sha] = parsedShader;
  72. gltfRuntime.shaderscount++;
  73. }
  74. };
  75. var parseObject = (parsedObjects: any, runtimeProperty: string, gltfRuntime: IGLTFRuntime) => {
  76. for (var object in parsedObjects) {
  77. var parsedObject = parsedObjects[object];
  78. gltfRuntime[runtimeProperty][object] = parsedObject;
  79. }
  80. };
  81. /**
  82. * Utils
  83. */
  84. var normalizeUVs = (buffer: any) => {
  85. if (!buffer) {
  86. return;
  87. }
  88. for (var i = 0; i < buffer.length / 2; i++) {
  89. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  90. }
  91. };
  92. var replaceInString = (str: string, searchValue: string, replaceValue: string) => {
  93. while (str.indexOf(searchValue) !== -1) {
  94. str = str.replace(searchValue, replaceValue);
  95. }
  96. return str;
  97. };
  98. var getAttribute = (attributeParameter: IGLTFTechniqueParameter) => {
  99. if (attributeParameter.semantic === "NORMAL") {
  100. return "normal";
  101. } else if (attributeParameter.semantic === "POSITION") {
  102. return "position";
  103. } else if (attributeParameter.semantic === "JOINT") {
  104. return "matricesIndices";
  105. } else if (attributeParameter.semantic === "WEIGHT") {
  106. return "matricesWeights";
  107. } else if (attributeParameter.semantic === "COLOR") {
  108. return "color";
  109. } else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  110. var channel = Number(attributeParameter.semantic.split("_")[1]);
  111. return "uv" + (channel === 0 ? "" : channel + 1);
  112. }
  113. };
  114. /**
  115. * Returns the animation path (glTF -> Babylon)
  116. */
  117. var getAnimationPath = (path: string): string => {
  118. var index = glTFAnimationPaths.indexOf(path);
  119. if (index !== -1) {
  120. return babylonAnimationPaths[index];
  121. }
  122. return path;
  123. };
  124. /**
  125. * Loads and creates animations
  126. */
  127. var loadAnimations = (gltfRuntime: IGLTFRuntime) => {
  128. for (var anim in gltfRuntime.animations) {
  129. var animation: IGLTFAnimation = gltfRuntime.animations[anim];
  130. var lastAnimation: Animation = null;
  131. for (var i = 0; i < animation.channels.length; i++) {
  132. // Get parameters and load buffers
  133. var channel = animation.channels[i];
  134. var sampler: IGLTFAnimationSampler = animation.samplers[channel.sampler];
  135. if (!sampler) {
  136. continue;
  137. }
  138. var inputData: string = null;
  139. var outputData: string = null;
  140. if (animation.parameters) {
  141. inputData = animation.parameters[sampler.input];
  142. outputData = animation.parameters[sampler.output];
  143. }
  144. else {
  145. inputData = sampler.input;
  146. outputData = sampler.output;
  147. }
  148. var bufferInput = GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  149. var bufferOutput = GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  150. var targetID = channel.target.id;
  151. var targetNode: any = gltfRuntime.scene.getNodeByID(targetID);
  152. if (targetNode === null) {
  153. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  154. }
  155. if (targetNode === null) {
  156. Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  157. continue;
  158. }
  159. var isBone = targetNode instanceof Bone;
  160. // Get target path (position, rotation or scaling)
  161. var targetPath = channel.target.path;
  162. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  163. if (targetPathIndex !== -1) {
  164. targetPath = babylonAnimationPaths[targetPathIndex];
  165. }
  166. // Determine animation type
  167. var animationType = Animation.ANIMATIONTYPE_MATRIX;
  168. if (!isBone) {
  169. if (targetPath === "rotationQuaternion") {
  170. animationType = Animation.ANIMATIONTYPE_QUATERNION;
  171. targetNode.rotationQuaternion = new Quaternion();
  172. }
  173. else {
  174. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  175. }
  176. }
  177. // Create animation and key frames
  178. var babylonAnimation: Animation = null;
  179. var keys = [];
  180. var arrayOffset = 0;
  181. var modifyKey = false;
  182. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  183. babylonAnimation = lastAnimation;
  184. modifyKey = true;
  185. }
  186. if (!modifyKey) {
  187. babylonAnimation = new Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, Animation.ANIMATIONLOOPMODE_CYCLE);
  188. }
  189. // For each frame
  190. for (var j = 0; j < bufferInput.length; j++) {
  191. var value: any = null;
  192. if (targetPath === "rotationQuaternion") { // VEC4
  193. value = Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  194. arrayOffset += 4;
  195. }
  196. else { // Position and scaling are VEC3
  197. value = Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  198. arrayOffset += 3;
  199. }
  200. if (isBone) {
  201. var bone = <Bone>targetNode;
  202. var translation = Vector3.Zero();
  203. var rotationQuaternion = new Quaternion();
  204. var scaling = Vector3.Zero();
  205. // Warning on decompose
  206. var mat = bone.getBaseMatrix();
  207. if (modifyKey) {
  208. mat = lastAnimation.getKeys()[j].value;
  209. }
  210. mat.decompose(scaling, rotationQuaternion, translation);
  211. if (targetPath === "position") {
  212. translation = value;
  213. }
  214. else if (targetPath === "rotationQuaternion") {
  215. rotationQuaternion = value;
  216. }
  217. else {
  218. scaling = value;
  219. }
  220. value = Matrix.Compose(scaling, rotationQuaternion, translation);
  221. }
  222. if (!modifyKey) {
  223. keys.push({
  224. frame: bufferInput[j],
  225. value: value
  226. });
  227. }
  228. else {
  229. lastAnimation.getKeys()[j].value = value;
  230. }
  231. }
  232. // Finish
  233. if (!modifyKey) {
  234. babylonAnimation.setKeys(keys);
  235. targetNode.animations.push(babylonAnimation);
  236. }
  237. lastAnimation = babylonAnimation;
  238. gltfRuntime.scene.stopAnimation(targetNode);
  239. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  240. }
  241. }
  242. };
  243. /**
  244. * Returns the bones transformation matrix
  245. */
  246. var configureBoneTransformation = (node: IGLTFNode): Matrix => {
  247. var mat: Matrix = null;
  248. if (node.translation || node.rotation || node.scale) {
  249. var scale = Vector3.FromArray(node.scale || [1, 1, 1]);
  250. var rotation = Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  251. var position = Vector3.FromArray(node.translation || [0, 0, 0]);
  252. mat = Matrix.Compose(scale, rotation, position);
  253. }
  254. else {
  255. mat = Matrix.FromArray(node.matrix);
  256. }
  257. return mat;
  258. };
  259. /**
  260. * Returns the parent bone
  261. */
  262. var getParentBone = (gltfRuntime: IGLTFRuntime, skins: IGLTFSkins, jointName: string, newSkeleton: Skeleton): Bone => {
  263. // Try to find
  264. for (var i = 0; i < newSkeleton.bones.length; i++) {
  265. if (newSkeleton.bones[i].name === jointName) {
  266. return newSkeleton.bones[i];
  267. }
  268. }
  269. // Not found, search in gltf nodes
  270. var nodes = gltfRuntime.nodes;
  271. for (var nde in nodes) {
  272. var node: IGLTFNode = nodes[nde];
  273. if (!node.jointName) {
  274. continue;
  275. }
  276. var children = node.children;
  277. for (var i = 0; i < children.length; i++) {
  278. var child: IGLTFNode = gltfRuntime.nodes[children[i]];
  279. if (!child.jointName) {
  280. continue;
  281. }
  282. if (child.jointName === jointName) {
  283. var mat = configureBoneTransformation(node);
  284. var bone = new Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  285. bone.id = nde;
  286. return bone;
  287. }
  288. }
  289. }
  290. return null;
  291. }
  292. /**
  293. * Returns the appropriate root node
  294. */
  295. var getNodeToRoot = (nodesToRoot: INodeToRoot[], id: string): Bone => {
  296. for (var i = 0; i < nodesToRoot.length; i++) {
  297. var nodeToRoot = nodesToRoot[i];
  298. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  299. var child = nodeToRoot.node.children[j];
  300. if (child === id) {
  301. return nodeToRoot.bone;
  302. }
  303. }
  304. }
  305. return null;
  306. };
  307. /**
  308. * Returns the node with the joint name
  309. */
  310. var getJointNode = (gltfRuntime: IGLTFRuntime, jointName: string): IJointNode => {
  311. var nodes = gltfRuntime.nodes;
  312. var node: IGLTFNode = nodes[jointName];
  313. if (node) {
  314. return {
  315. node: node,
  316. id: jointName
  317. };
  318. }
  319. for (var nde in nodes) {
  320. node = nodes[nde];
  321. if (node.jointName === jointName) {
  322. return {
  323. node: node,
  324. id: nde
  325. };
  326. }
  327. }
  328. return null;
  329. }
  330. /**
  331. * Checks if a nodes is in joints
  332. */
  333. var nodeIsInJoints = (skins: IGLTFSkins, id: string): boolean => {
  334. for (var i = 0; i < skins.jointNames.length; i++) {
  335. if (skins.jointNames[i] === id) {
  336. return true;
  337. }
  338. }
  339. return false;
  340. }
  341. /**
  342. * Fills the nodes to root for bones and builds hierarchy
  343. */
  344. var getNodesToRoot = (gltfRuntime: IGLTFRuntime, newSkeleton: Skeleton, skins: IGLTFSkins, nodesToRoot: INodeToRoot[]) => {
  345. // Creates nodes for root
  346. for (var nde in gltfRuntime.nodes) {
  347. var node: IGLTFNode = gltfRuntime.nodes[nde];
  348. var id = nde;
  349. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  350. continue;
  351. }
  352. // Create node to root bone
  353. var mat = configureBoneTransformation(node);
  354. var bone = new Bone(node.name, newSkeleton, null, mat);
  355. bone.id = id;
  356. nodesToRoot.push({ bone: bone, node: node, id: id });
  357. }
  358. // Parenting
  359. for (var i = 0; i < nodesToRoot.length; i++) {
  360. var nodeToRoot = nodesToRoot[i];
  361. var children = nodeToRoot.node.children;
  362. for (var j = 0; j < children.length; j++) {
  363. var child: INodeToRoot = null;
  364. for (var k = 0; k < nodesToRoot.length; k++) {
  365. if (nodesToRoot[k].id === children[j]) {
  366. child = nodesToRoot[k];
  367. break;
  368. }
  369. }
  370. if (child) {
  371. (<any>child.bone)._parent = nodeToRoot.bone;
  372. nodeToRoot.bone.children.push(child.bone);
  373. }
  374. }
  375. }
  376. };
  377. var printMat = (m: Float32Array) => {
  378. console.log(
  379. m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  380. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  381. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  382. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n"
  383. );
  384. }
  385. /**
  386. * Imports a skeleton
  387. */
  388. var importSkeleton = (gltfRuntime: IGLTFRuntime, skins: IGLTFSkins, mesh: Mesh, newSkeleton: Skeleton, id: string): Skeleton => {
  389. if (!newSkeleton) {
  390. newSkeleton = new Skeleton(skins.name, "", gltfRuntime.scene);
  391. }
  392. if (!skins.babylonSkeleton) {
  393. return newSkeleton;
  394. }
  395. // Matrices
  396. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  397. var buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  398. var bindShapeMatrix = Matrix.FromArray(skins.bindShapeMatrix);
  399. // Find the root bones
  400. var nodesToRoot: INodeToRoot[] = [];
  401. var nodesToRootToAdd: Bone[] = [];
  402. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  403. newSkeleton.bones = [];
  404. // Joints
  405. for (var i = 0; i < skins.jointNames.length; i++) {
  406. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  407. var node = jointNode.node;
  408. if (!node) {
  409. Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  410. continue;
  411. }
  412. var id = jointNode.id;
  413. // Optimize, if the bone already exists...
  414. var existingBone = gltfRuntime.scene.getBoneByID(id);
  415. if (existingBone) {
  416. newSkeleton.bones.push(existingBone);
  417. continue;
  418. }
  419. // Search for parent bone
  420. var foundBone = false;
  421. var parentBone: Bone = null;
  422. for (var j = 0; j < i; j++) {
  423. var joint: IGLTFNode = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  424. if (!joint) {
  425. Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  426. continue;
  427. }
  428. var children = joint.children;
  429. if (!children) {
  430. continue;
  431. }
  432. foundBone = false;
  433. for (var k = 0; k < children.length; k++) {
  434. if (children[k] === id) {
  435. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  436. foundBone = true;
  437. break;
  438. }
  439. }
  440. if (foundBone) {
  441. break;
  442. }
  443. }
  444. // Create bone
  445. var mat = configureBoneTransformation(node);
  446. if (!parentBone && nodesToRoot.length > 0) {
  447. parentBone = getNodeToRoot(nodesToRoot, id);
  448. if (parentBone) {
  449. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  450. nodesToRootToAdd.push(parentBone);
  451. }
  452. }
  453. }
  454. var bone = new Bone(node.jointName, newSkeleton, parentBone, mat);
  455. bone.id = id;
  456. }
  457. // Polish
  458. var bones = newSkeleton.bones;
  459. newSkeleton.bones = [];
  460. for (var i = 0; i < skins.jointNames.length; i++) {
  461. var jointNode: IJointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  462. if (!jointNode) {
  463. continue;
  464. }
  465. for (var j = 0; j < bones.length; j++) {
  466. if (bones[j].id === jointNode.id) {
  467. newSkeleton.bones.push(bones[j]);
  468. break;
  469. }
  470. }
  471. }
  472. newSkeleton.prepare();
  473. // Finish
  474. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  475. newSkeleton.bones.push(nodesToRootToAdd[i]);
  476. }
  477. return newSkeleton;
  478. };
  479. /**
  480. * Imports a mesh and its geometries
  481. */
  482. var importMesh = (gltfRuntime: IGLTFRuntime, node: IGLTFNode, meshes: string[], id: string, newMesh: Mesh): Mesh => {
  483. if (!newMesh) {
  484. newMesh = new Mesh(node.name, gltfRuntime.scene);
  485. newMesh.id = id;
  486. }
  487. if (!node.babylonNode) {
  488. return newMesh;
  489. }
  490. var multiMat = new MultiMaterial("multimat" + id, gltfRuntime.scene);
  491. if (!newMesh.material) {
  492. newMesh.material = multiMat;
  493. }
  494. var vertexData = new VertexData();
  495. var geometry = new Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  496. var verticesStarts = [];
  497. var verticesCounts = [];
  498. var indexStarts = [];
  499. var indexCounts = [];
  500. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  501. var meshID = meshes[meshIndex];
  502. var mesh: IGLTFMesh = gltfRuntime.meshes[meshID];
  503. if (!mesh) {
  504. continue;
  505. }
  506. // Positions, normals and UVs
  507. for (var i = 0; i < mesh.primitives.length; i++) {
  508. // Temporary vertex data
  509. var tempVertexData = new VertexData();
  510. var primitive = mesh.primitives[i];
  511. if (primitive.mode !== 4) {
  512. // continue;
  513. }
  514. var attributes = primitive.attributes;
  515. var accessor: IGLTFAccessor = null;
  516. var buffer: any = null;
  517. // Set positions, normal and uvs
  518. for (var semantic in attributes) {
  519. // Link accessor and buffer view
  520. accessor = gltfRuntime.accessors[attributes[semantic]];
  521. buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  522. if (semantic === "NORMAL") {
  523. tempVertexData.normals = new Float32Array(buffer.length);
  524. (<Float32Array>tempVertexData.normals).set(buffer);
  525. }
  526. else if (semantic === "POSITION") {
  527. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  528. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  529. for (var j = 0; j < buffer.length; j += 4) {
  530. tempVertexData.positions[j] = buffer[j];
  531. tempVertexData.positions[j + 1] = buffer[j + 1];
  532. tempVertexData.positions[j + 2] = buffer[j + 2];
  533. }
  534. }
  535. else {
  536. tempVertexData.positions = new Float32Array(buffer.length);
  537. (<Float32Array>tempVertexData.positions).set(buffer);
  538. }
  539. verticesCounts.push(tempVertexData.positions.length);
  540. }
  541. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  542. var channel = Number(semantic.split("_")[1]);
  543. var uvKind = VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  544. var uvs = new Float32Array(buffer.length);
  545. (<Float32Array>uvs).set(buffer);
  546. normalizeUVs(uvs);
  547. tempVertexData.set(uvs, uvKind);
  548. }
  549. else if (semantic === "JOINT") {
  550. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  551. (<Float32Array>tempVertexData.matricesIndices).set(buffer);
  552. }
  553. else if (semantic === "WEIGHT") {
  554. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  555. (<Float32Array>tempVertexData.matricesWeights).set(buffer);
  556. }
  557. else if (semantic === "COLOR") {
  558. tempVertexData.colors = new Float32Array(buffer.length);
  559. (<Float32Array>tempVertexData.colors).set(buffer);
  560. }
  561. }
  562. // Indices
  563. accessor = gltfRuntime.accessors[primitive.indices];
  564. if (accessor) {
  565. buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  566. tempVertexData.indices = new Int32Array(buffer.length);
  567. (<Float32Array>tempVertexData.indices).set(buffer);
  568. indexCounts.push(tempVertexData.indices.length);
  569. }
  570. else {
  571. // Set indices on the fly
  572. var indices: number[] = [];
  573. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  574. indices.push(j);
  575. }
  576. tempVertexData.indices = new Int32Array(indices);
  577. indexCounts.push(tempVertexData.indices.length);
  578. }
  579. vertexData.merge(tempVertexData);
  580. tempVertexData = undefined;
  581. // Sub material
  582. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  583. multiMat.subMaterials.push(material === null ? GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  584. // Update vertices start and index start
  585. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  586. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  587. }
  588. }
  589. // Apply geometry
  590. geometry.setAllVerticesData(vertexData, false);
  591. newMesh.computeWorldMatrix(true);
  592. // Apply submeshes
  593. newMesh.subMeshes = [];
  594. var index = 0;
  595. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  596. var meshID = meshes[meshIndex];
  597. var mesh: IGLTFMesh = gltfRuntime.meshes[meshID];
  598. if (!mesh) {
  599. continue;
  600. }
  601. for (var i = 0; i < mesh.primitives.length; i++) {
  602. if (mesh.primitives[i].mode !== 4) {
  603. //continue;
  604. }
  605. var subMesh = new SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  606. index++;
  607. }
  608. }
  609. // Finish
  610. return newMesh;
  611. };
  612. /**
  613. * Configure node transformation from position, rotation and scaling
  614. */
  615. var configureNode = (newNode: any, position: Vector3, rotation: Quaternion, scaling: Vector3) => {
  616. if (newNode.position) {
  617. newNode.position = position;
  618. }
  619. if (newNode.rotationQuaternion || newNode.rotation) {
  620. newNode.rotationQuaternion = rotation;
  621. }
  622. if (newNode.scaling) {
  623. newNode.scaling = scaling;
  624. }
  625. };
  626. /**
  627. * Configures node from transformation matrix
  628. */
  629. var configureNodeFromMatrix = (newNode: Mesh, node: IGLTFNode, parent: Node) => {
  630. if (node.matrix) {
  631. var position = new Vector3(0, 0, 0);
  632. var rotation = new Quaternion();
  633. var scaling = new Vector3(0, 0, 0);
  634. var mat = Matrix.FromArray(node.matrix);
  635. mat.decompose(scaling, rotation, position);
  636. configureNode(newNode, position, rotation, scaling);
  637. }
  638. else {
  639. configureNode(newNode, Vector3.FromArray(node.translation), Quaternion.FromArray(node.rotation), Vector3.FromArray(node.scale));
  640. }
  641. newNode.computeWorldMatrix(true);
  642. };
  643. /**
  644. * Imports a node
  645. */
  646. var importNode = (gltfRuntime: IGLTFRuntime, node: IGLTFNode, id: string, parent: Node): Node => {
  647. var lastNode: Node = null;
  648. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  649. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  650. return null;
  651. }
  652. }
  653. // Meshes
  654. if (node.skin) {
  655. if (node.meshes) {
  656. var skin: IGLTFSkins = gltfRuntime.skins[node.skin];
  657. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, <Mesh>node.babylonNode);
  658. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  659. if (newMesh.skeleton === null) {
  660. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  661. if (!skin.babylonSkeleton) {
  662. skin.babylonSkeleton = newMesh.skeleton;
  663. }
  664. }
  665. lastNode = newMesh;
  666. }
  667. }
  668. else if (node.meshes) {
  669. /**
  670. * Improve meshes property
  671. */
  672. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, <Mesh>node.babylonNode);
  673. lastNode = newMesh;
  674. }
  675. // Lights
  676. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  677. var light: IGLTFLight = gltfRuntime.lights[node.light];
  678. if (light) {
  679. if (light.type === "ambient") {
  680. var ambienLight: IGLTFAmbienLight = light[light.type];
  681. var hemiLight = new HemisphericLight(node.light, Vector3.Zero(), gltfRuntime.scene);
  682. hemiLight.name = node.name;
  683. if (ambienLight.color) {
  684. hemiLight.diffuse = Color3.FromArray(ambienLight.color);
  685. }
  686. lastNode = hemiLight;
  687. }
  688. else if (light.type === "directional") {
  689. var directionalLight: IGLTFDirectionalLight = light[light.type];
  690. var dirLight = new DirectionalLight(node.light, Vector3.Zero(), gltfRuntime.scene);
  691. dirLight.name = node.name;
  692. if (directionalLight.color) {
  693. dirLight.diffuse = Color3.FromArray(directionalLight.color);
  694. }
  695. lastNode = dirLight;
  696. }
  697. else if (light.type === "point") {
  698. var pointLight: IGLTFPointLight = light[light.type];
  699. var ptLight = new PointLight(node.light, Vector3.Zero(), gltfRuntime.scene);
  700. ptLight.name = node.name;
  701. if (pointLight.color) {
  702. ptLight.diffuse = Color3.FromArray(pointLight.color);
  703. }
  704. lastNode = ptLight;
  705. }
  706. else if (light.type === "spot") {
  707. var spotLight: IGLTFSpotLight = light[light.type];
  708. var spLight = new SpotLight(node.light, Vector3.Zero(), Vector3.Zero(), 0, 0, gltfRuntime.scene);
  709. spLight.name = node.name;
  710. if (spotLight.color) {
  711. spLight.diffuse = Color3.FromArray(spotLight.color);
  712. }
  713. if (spotLight.fallOfAngle) {
  714. spLight.angle = spotLight.fallOfAngle;
  715. }
  716. if (spotLight.fallOffExponent) {
  717. spLight.exponent = spotLight.fallOffExponent;
  718. }
  719. lastNode = spLight;
  720. }
  721. }
  722. }
  723. // Cameras
  724. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  725. var camera: IGLTFCamera = gltfRuntime.cameras[node.camera];
  726. if (camera) {
  727. if (camera.type === "orthographic") {
  728. var orthographicCamera: IGLTFCameraOrthographic = camera[camera.type];
  729. var orthoCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene);
  730. orthoCamera.name = node.name;
  731. orthoCamera.mode = Camera.ORTHOGRAPHIC_CAMERA;
  732. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  733. lastNode = orthoCamera;
  734. }
  735. else if (camera.type === "perspective") {
  736. var perspectiveCamera: IGLTFCameraPerspective = camera[camera.type];
  737. var persCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene);
  738. persCamera.name = node.name;
  739. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  740. if (!perspectiveCamera.aspectRatio) {
  741. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  742. }
  743. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  744. persCamera.maxZ = perspectiveCamera.zfar;
  745. persCamera.minZ = perspectiveCamera.znear;
  746. }
  747. lastNode = persCamera;
  748. }
  749. }
  750. }
  751. // Empty node
  752. if (!node.jointName) {
  753. if (node.babylonNode) {
  754. return node.babylonNode;
  755. }
  756. else if (lastNode === null) {
  757. var dummy = new Mesh(node.name, gltfRuntime.scene);
  758. node.babylonNode = dummy;
  759. lastNode = dummy;
  760. }
  761. }
  762. if (lastNode !== null) {
  763. if (node.matrix && lastNode instanceof Mesh) {
  764. configureNodeFromMatrix(lastNode, node, parent);
  765. }
  766. else {
  767. var translation = node.translation || [0, 0, 0];
  768. var rotation = node.rotation || [0, 0, 0, 1];
  769. var scale = node.scale || [1, 1, 1];
  770. configureNode(lastNode, Vector3.FromArray(translation), Quaternion.FromArray(rotation), Vector3.FromArray(scale));
  771. }
  772. lastNode.updateCache(true);
  773. node.babylonNode = lastNode;
  774. }
  775. return lastNode;
  776. };
  777. /**
  778. * Traverses nodes and creates them
  779. */
  780. var traverseNodes = (gltfRuntime: IGLTFRuntime, id: string, parent: Node, meshIncluded?: boolean) => {
  781. var node: IGLTFNode = gltfRuntime.nodes[id];
  782. var newNode: Node = null;
  783. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  784. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  785. meshIncluded = true;
  786. }
  787. else {
  788. meshIncluded = false;
  789. }
  790. }
  791. else {
  792. meshIncluded = true;
  793. }
  794. if (!node.jointName && meshIncluded) {
  795. newNode = importNode(gltfRuntime, node, id, parent);
  796. if (newNode !== null) {
  797. newNode.id = id;
  798. newNode.parent = parent;
  799. }
  800. }
  801. if (node.children) {
  802. for (var i = 0; i < node.children.length; i++) {
  803. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  804. }
  805. }
  806. };
  807. /**
  808. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  809. */
  810. var postLoad = (gltfRuntime: IGLTFRuntime) => {
  811. // Nodes
  812. var currentScene: IGLTFScene = <IGLTFScene>gltfRuntime.currentScene;
  813. if (currentScene) {
  814. for (var i = 0; i < currentScene.nodes.length; i++) {
  815. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  816. }
  817. }
  818. else {
  819. for (var thing in gltfRuntime.scenes) {
  820. currentScene = <IGLTFScene>gltfRuntime.scenes[thing];
  821. for (var i = 0; i < currentScene.nodes.length; i++) {
  822. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  823. }
  824. }
  825. }
  826. // Set animations
  827. loadAnimations(gltfRuntime);
  828. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  829. var skeleton = gltfRuntime.scene.skeletons[i];
  830. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  831. }
  832. };
  833. /**
  834. * onBind shaderrs callback to set uniforms and matrices
  835. */
  836. var onBindShaderMaterial = (mesh: Mesh, gltfRuntime: IGLTFRuntime, unTreatedUniforms: Object, shaderMaterial: ShaderMaterial, technique: IGLTFTechnique, material: IGLTFMaterial, onSuccess: (shaderMaterial: ShaderMaterial) => void) => {
  837. var materialValues = material.values || technique.parameters;
  838. for (var unif in unTreatedUniforms) {
  839. var uniform: IGLTFTechniqueParameter = unTreatedUniforms[unif];
  840. var type = uniform.type;
  841. if (type === EParameterType.FLOAT_MAT2 || type === EParameterType.FLOAT_MAT3 || type === EParameterType.FLOAT_MAT4) {
  842. if (uniform.semantic && !uniform.source && !uniform.node) {
  843. GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  844. }
  845. else if (uniform.semantic && (uniform.source || uniform.node)) {
  846. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  847. if (source === null) {
  848. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  849. }
  850. if (source === null) {
  851. continue;
  852. }
  853. GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  854. }
  855. }
  856. else {
  857. var value = materialValues[technique.uniforms[unif]];
  858. if (!value) {
  859. continue;
  860. }
  861. if (type === EParameterType.SAMPLER_2D) {
  862. var texture: Texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  863. if (texture === null || texture === undefined) {
  864. continue;
  865. }
  866. shaderMaterial.getEffect().setTexture(unif, texture);
  867. }
  868. else {
  869. GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  870. }
  871. }
  872. }
  873. onSuccess(shaderMaterial);
  874. };
  875. /**
  876. * Prepare uniforms to send the only one time
  877. * Loads the appropriate textures
  878. */
  879. var prepareShaderMaterialUniforms = (gltfRuntime: IGLTFRuntime, shaderMaterial: ShaderMaterial, technique: IGLTFTechnique, material: IGLTFMaterial, unTreatedUniforms: Object) => {
  880. var materialValues = material.values || technique.parameters;
  881. var techniqueUniforms = technique.uniforms;
  882. /**
  883. * Prepare values here (not matrices)
  884. */
  885. for (var unif in unTreatedUniforms) {
  886. var uniform: IGLTFTechniqueParameter = unTreatedUniforms[unif];
  887. var type = uniform.type;
  888. var value = materialValues[techniqueUniforms[unif]];
  889. if (value === undefined) {
  890. // In case the value is the same for all materials
  891. value = <any>uniform.value;
  892. }
  893. if (!value) {
  894. continue;
  895. }
  896. var onLoadTexture = (uniformName: string) => {
  897. return (texture: Texture) => {
  898. if (uniform.value) {
  899. // Static uniform
  900. shaderMaterial.setTexture(uniformName, texture);
  901. delete unTreatedUniforms[uniformName];
  902. }
  903. }
  904. };
  905. // Texture (sampler2D)
  906. if (type === EParameterType.SAMPLER_2D) {
  907. GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), () => onLoadTexture(null));
  908. }
  909. // Others
  910. else {
  911. if (uniform.value && GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  912. // Static uniform
  913. delete unTreatedUniforms[unif];
  914. }
  915. }
  916. }
  917. };
  918. /**
  919. * Shader compilation failed
  920. */
  921. var onShaderCompileError = (program: IGLTFProgram, shaderMaterial: ShaderMaterial, onError: (message: string) => void) => {
  922. return (effect: Effect, error: string) => {
  923. shaderMaterial.dispose(true);
  924. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  925. };
  926. };
  927. /**
  928. * Shader compilation success
  929. */
  930. var onShaderCompileSuccess = (gltfRuntime: IGLTFRuntime, shaderMaterial: ShaderMaterial, technique: IGLTFTechnique, material: IGLTFMaterial, unTreatedUniforms: Object, onSuccess: (shaderMaterial: ShaderMaterial) => void) => {
  931. return (_: Effect) => {
  932. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  933. shaderMaterial.onBind = (mesh: Mesh) => {
  934. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  935. };
  936. };
  937. };
  938. /**
  939. * Returns the appropriate uniform if already handled by babylon
  940. */
  941. var parseShaderUniforms = (tokenizer: Tokenizer, technique: IGLTFTechnique, unTreatedUniforms: Object): string => {
  942. for (var unif in technique.uniforms) {
  943. var uniform = technique.uniforms[unif];
  944. var uniformParameter: IGLTFTechniqueParameter = technique.parameters[uniform];
  945. if (tokenizer.currentIdentifier === unif) {
  946. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  947. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  948. if (transformIndex !== -1) {
  949. delete unTreatedUniforms[unif];
  950. return babylonTransforms[transformIndex];
  951. }
  952. }
  953. }
  954. }
  955. return tokenizer.currentIdentifier;
  956. };
  957. /**
  958. * All shaders loaded. Create materials one by one
  959. */
  960. var importMaterials = (gltfRuntime: IGLTFRuntime) => {
  961. // Create materials
  962. for (var mat in gltfRuntime.materials) {
  963. GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, (material: Material) => { }, () => { });
  964. }
  965. };
  966. /**
  967. * Implementation of the base glTF spec
  968. */
  969. export class GLTFLoaderBase {
  970. public static CreateRuntime(parsedData: any, scene: Scene, rootUrl: string): IGLTFRuntime {
  971. var gltfRuntime: IGLTFRuntime = {
  972. extensions: {},
  973. accessors: {},
  974. buffers: {},
  975. bufferViews: {},
  976. meshes: {},
  977. lights: {},
  978. cameras: {},
  979. nodes: {},
  980. images: {},
  981. textures: {},
  982. shaders: {},
  983. programs: {},
  984. samplers: {},
  985. techniques: {},
  986. materials: {},
  987. animations: {},
  988. skins: {},
  989. extensionsUsed: [],
  990. scenes: {},
  991. buffersCount: 0,
  992. shaderscount: 0,
  993. scene: scene,
  994. rootUrl: rootUrl,
  995. loadedBufferCount: 0,
  996. loadedBufferViews: {},
  997. loadedShaderCount: 0,
  998. importOnlyMeshes: false,
  999. dummyNodes: []
  1000. }
  1001. // Parse
  1002. if (parsedData.extensions) {
  1003. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1004. }
  1005. if (parsedData.extensionsUsed) {
  1006. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1007. }
  1008. if (parsedData.buffers) {
  1009. parseBuffers(parsedData.buffers, gltfRuntime);
  1010. }
  1011. if (parsedData.bufferViews) {
  1012. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1013. }
  1014. if (parsedData.accessors) {
  1015. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1016. }
  1017. if (parsedData.meshes) {
  1018. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1019. }
  1020. if (parsedData.lights) {
  1021. parseObject(parsedData.lights, "lights", gltfRuntime);
  1022. }
  1023. if (parsedData.cameras) {
  1024. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1025. }
  1026. if (parsedData.nodes) {
  1027. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1028. }
  1029. if (parsedData.images) {
  1030. parseObject(parsedData.images, "images", gltfRuntime);
  1031. }
  1032. if (parsedData.textures) {
  1033. parseObject(parsedData.textures, "textures", gltfRuntime);
  1034. }
  1035. if (parsedData.shaders) {
  1036. parseShaders(parsedData.shaders, gltfRuntime);
  1037. }
  1038. if (parsedData.programs) {
  1039. parseObject(parsedData.programs, "programs", gltfRuntime);
  1040. }
  1041. if (parsedData.samplers) {
  1042. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1043. }
  1044. if (parsedData.techniques) {
  1045. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1046. }
  1047. if (parsedData.materials) {
  1048. parseObject(parsedData.materials, "materials", gltfRuntime);
  1049. }
  1050. if (parsedData.animations) {
  1051. parseObject(parsedData.animations, "animations", gltfRuntime);
  1052. }
  1053. if (parsedData.skins) {
  1054. parseObject(parsedData.skins, "skins", gltfRuntime);
  1055. }
  1056. if (parsedData.scenes) {
  1057. gltfRuntime.scenes = parsedData.scenes;
  1058. }
  1059. if (parsedData.scene && parsedData.scenes) {
  1060. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1061. }
  1062. return gltfRuntime;
  1063. }
  1064. public static LoadBufferAsync(gltfRuntime: IGLTFRuntime, id: string, onSuccess: (buffer: ArrayBufferView) => void, onError: (message: string) => void, onProgress?: () => void): void {
  1065. var buffer: IGLTFBuffer = gltfRuntime.buffers[id];
  1066. if (GLTFUtils.IsBase64(buffer.uri)) {
  1067. setTimeout(() => onSuccess(new Uint8Array(GLTFUtils.DecodeBase64(buffer.uri))));
  1068. }
  1069. else {
  1070. Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, data => onSuccess(new Uint8Array(data)), onProgress, null, true, request => {
  1071. onError(request.status + " " + request.statusText);
  1072. });
  1073. }
  1074. }
  1075. public static LoadTextureBufferAsync(gltfRuntime: IGLTFRuntime, id: string, onSuccess: (buffer: ArrayBufferView) => void, onError: (message: string) => void): void {
  1076. var texture: IGLTFTexture = gltfRuntime.textures[id];
  1077. if (!texture || !texture.source) {
  1078. onError(null);
  1079. return;
  1080. }
  1081. if (texture.babylonTexture) {
  1082. onSuccess(null);
  1083. return;
  1084. }
  1085. var source: IGLTFImage = gltfRuntime.images[texture.source];
  1086. if (GLTFUtils.IsBase64(source.uri)) {
  1087. setTimeout(() => onSuccess(new Uint8Array(GLTFUtils.DecodeBase64(source.uri))));
  1088. }
  1089. else {
  1090. Tools.LoadFile(gltfRuntime.rootUrl + source.uri, data => onSuccess(new Uint8Array(data)), null, null, true, request => {
  1091. onError(request.status + " " + request.statusText);
  1092. });
  1093. }
  1094. }
  1095. public static CreateTextureAsync(gltfRuntime: IGLTFRuntime, id: string, buffer: ArrayBufferView, onSuccess: (texture: Texture) => void, onError: (message: string) => void): void {
  1096. var texture: IGLTFTexture = gltfRuntime.textures[id];
  1097. if (texture.babylonTexture) {
  1098. onSuccess(texture.babylonTexture);
  1099. return;
  1100. }
  1101. var sampler: IGLTFSampler = gltfRuntime.samplers[texture.sampler];
  1102. var createMipMaps =
  1103. (sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1104. (sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1105. (sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1106. (sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1107. var samplingMode = Texture.BILINEAR_SAMPLINGMODE;
  1108. var blob = new Blob([buffer]);
  1109. var blobURL = URL.createObjectURL(blob);
  1110. var revokeBlobURL = () => URL.revokeObjectURL(blobURL);
  1111. var newTexture = new Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1112. newTexture.wrapU = GLTFUtils.GetWrapMode(sampler.wrapS);
  1113. newTexture.wrapV = GLTFUtils.GetWrapMode(sampler.wrapT);
  1114. newTexture.name = id;
  1115. texture.babylonTexture = newTexture;
  1116. onSuccess(newTexture);
  1117. }
  1118. public static LoadShaderStringAsync(gltfRuntime: IGLTFRuntime, id: string, onSuccess: (shaderString: string) => void, onError: (message: string) => void): void {
  1119. var shader: IGLTFShader = gltfRuntime.shaders[id];
  1120. if (GLTFUtils.IsBase64(shader.uri)) {
  1121. var shaderString = atob(shader.uri.split(",")[1]);
  1122. onSuccess(shaderString);
  1123. }
  1124. else {
  1125. Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, request => {
  1126. onError(request.status + " " + request.statusText);
  1127. });
  1128. }
  1129. }
  1130. public static LoadMaterialAsync(gltfRuntime: IGLTFRuntime, id: string, onSuccess: (material: Material) => void, onError: (message: string) => void): void {
  1131. var material: IGLTFMaterial = gltfRuntime.materials[id];
  1132. var technique: IGLTFTechnique = gltfRuntime.techniques[material.technique];
  1133. if (!technique) {
  1134. var defaultMaterial = new StandardMaterial(id, gltfRuntime.scene);
  1135. defaultMaterial.diffuseColor = new Color3(0.5, 0.5, 0.5);
  1136. defaultMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;
  1137. onSuccess(defaultMaterial);
  1138. return;
  1139. }
  1140. var program: IGLTFProgram = gltfRuntime.programs[technique.program];
  1141. var states: IGLTFTechniqueStates = technique.states;
  1142. var vertexShader: string = Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1143. var pixelShader: string = Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1144. var newVertexShader = "";
  1145. var newPixelShader = "";
  1146. var vertexTokenizer = new Tokenizer(vertexShader);
  1147. var pixelTokenizer = new Tokenizer(pixelShader);
  1148. var unTreatedUniforms: Object = {};
  1149. var uniforms = [];
  1150. var attributes = [];
  1151. var samplers = [];
  1152. // Fill uniform, sampler2D and attributes
  1153. for (var unif in technique.uniforms) {
  1154. var uniform = technique.uniforms[unif];
  1155. var uniformParameter: IGLTFTechniqueParameter = technique.parameters[uniform];
  1156. unTreatedUniforms[unif] = uniformParameter;
  1157. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1158. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1159. if (transformIndex !== -1) {
  1160. uniforms.push(babylonTransforms[transformIndex]);
  1161. delete unTreatedUniforms[unif];
  1162. }
  1163. else {
  1164. uniforms.push(unif);
  1165. }
  1166. }
  1167. else if (uniformParameter.type === EParameterType.SAMPLER_2D) {
  1168. samplers.push(unif);
  1169. }
  1170. else {
  1171. uniforms.push(unif);
  1172. }
  1173. }
  1174. for (var attr in technique.attributes) {
  1175. var attribute = technique.attributes[attr];
  1176. var attributeParameter: IGLTFTechniqueParameter = technique.parameters[attribute];
  1177. if (attributeParameter.semantic) {
  1178. attributes.push(getAttribute(attributeParameter));
  1179. }
  1180. }
  1181. // Configure vertex shader
  1182. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1183. var tokenType = vertexTokenizer.currentToken;
  1184. if (tokenType !== ETokenType.IDENTIFIER) {
  1185. newVertexShader += vertexTokenizer.currentString;
  1186. continue;
  1187. }
  1188. var foundAttribute = false;
  1189. for (var attr in technique.attributes) {
  1190. var attribute = technique.attributes[attr];
  1191. var attributeParameter: IGLTFTechniqueParameter = technique.parameters[attribute];
  1192. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1193. newVertexShader += getAttribute(attributeParameter);
  1194. foundAttribute = true;
  1195. break;
  1196. }
  1197. }
  1198. if (foundAttribute) {
  1199. continue;
  1200. }
  1201. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1202. }
  1203. // Configure pixel shader
  1204. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1205. var tokenType = pixelTokenizer.currentToken;
  1206. if (tokenType !== ETokenType.IDENTIFIER) {
  1207. newPixelShader += pixelTokenizer.currentString;
  1208. continue;
  1209. }
  1210. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1211. }
  1212. // Create shader material
  1213. var shaderPath = {
  1214. vertex: program.vertexShader + id,
  1215. fragment: program.fragmentShader + id
  1216. };
  1217. var options = {
  1218. attributes: attributes,
  1219. uniforms: uniforms,
  1220. samplers: samplers,
  1221. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1222. };
  1223. Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1224. Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1225. var shaderMaterial = new ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1226. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1227. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1228. shaderMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;
  1229. if (states && states.functions) {
  1230. var functions = states.functions;
  1231. if (functions.cullFace && functions.cullFace[0] !== ECullingType.BACK) {
  1232. shaderMaterial.backFaceCulling = false;
  1233. }
  1234. var blendFunc = functions.blendFuncSeparate;
  1235. if (blendFunc) {
  1236. if (blendFunc[0] === EBlendingFunction.SRC_ALPHA && blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
  1237. shaderMaterial.alphaMode = Engine.ALPHA_COMBINE;
  1238. }
  1239. else if (blendFunc[0] === EBlendingFunction.ONE && blendFunc[1] === EBlendingFunction.ONE && blendFunc[2] === EBlendingFunction.ZERO && blendFunc[3] === EBlendingFunction.ONE) {
  1240. shaderMaterial.alphaMode = Engine.ALPHA_ONEONE;
  1241. }
  1242. else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA && blendFunc[1] === EBlendingFunction.ONE && blendFunc[2] === EBlendingFunction.ZERO && blendFunc[3] === EBlendingFunction.ONE) {
  1243. shaderMaterial.alphaMode = Engine.ALPHA_ADD;
  1244. }
  1245. else if (blendFunc[0] === EBlendingFunction.ZERO && blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
  1246. shaderMaterial.alphaMode = Engine.ALPHA_SUBTRACT;
  1247. }
  1248. else if (blendFunc[0] === EBlendingFunction.DST_COLOR && blendFunc[1] === EBlendingFunction.ZERO && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
  1249. shaderMaterial.alphaMode = Engine.ALPHA_MULTIPLY;
  1250. }
  1251. else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA && blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
  1252. shaderMaterial.alphaMode = Engine.ALPHA_MAXIMIZED;
  1253. }
  1254. }
  1255. }
  1256. }
  1257. }
  1258. /**
  1259. * glTF V1 Loader
  1260. */
  1261. export class GLTFLoader implements IGLTFLoader {
  1262. public static Extensions: { [name: string]: GLTFLoaderExtension } = {};
  1263. public static RegisterExtension(extension: GLTFLoaderExtension): void {
  1264. if (GLTFLoader.Extensions[extension.name]) {
  1265. Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1266. return;
  1267. }
  1268. GLTFLoader.Extensions[extension.name] = extension;
  1269. }
  1270. public importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onProgress: (event: ProgressEvent) => void, onError: (message: string) => void): boolean {
  1271. scene.useRightHandedSystem = true;
  1272. var gltfRuntime = GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, gltfRuntime => {
  1273. gltfRuntime.importOnlyMeshes = true;
  1274. if (meshesNames === "") {
  1275. gltfRuntime.importMeshesNames = [];
  1276. }
  1277. else if (typeof meshesNames === "string") {
  1278. gltfRuntime.importMeshesNames = [meshesNames];
  1279. }
  1280. else if (meshesNames && !(meshesNames instanceof Array)) {
  1281. gltfRuntime.importMeshesNames = [meshesNames];
  1282. }
  1283. else {
  1284. gltfRuntime.importMeshesNames = [];
  1285. Tools.Warn("Argument meshesNames must be of type string or string[]");
  1286. }
  1287. // Create nodes
  1288. this._createNodes(gltfRuntime);
  1289. var meshes = [];
  1290. var skeletons = [];
  1291. // Fill arrays of meshes and skeletons
  1292. for (var nde in gltfRuntime.nodes) {
  1293. var node: IGLTFNode = gltfRuntime.nodes[nde];
  1294. if (node.babylonNode instanceof AbstractMesh) {
  1295. meshes.push(<AbstractMesh>node.babylonNode);
  1296. }
  1297. }
  1298. for (var skl in gltfRuntime.skins) {
  1299. var skin: IGLTFSkins = gltfRuntime.skins[skl];
  1300. if (skin.babylonSkeleton instanceof Skeleton) {
  1301. skeletons.push(skin.babylonSkeleton);
  1302. }
  1303. }
  1304. // Load buffers, shaders, materials, etc.
  1305. this._loadBuffersAsync(gltfRuntime, () => {
  1306. this._loadShadersAsync(gltfRuntime, () => {
  1307. importMaterials(gltfRuntime);
  1308. postLoad(gltfRuntime);
  1309. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1310. onSuccess(meshes, null, skeletons);
  1311. }
  1312. });
  1313. }, onProgress);
  1314. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1315. onSuccess(meshes, null, skeletons);
  1316. }
  1317. }, onError);
  1318. return true;
  1319. }
  1320. public loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: () => void, onProgress: (event: ProgressEvent) => void, onError: (message: string) => void): void {
  1321. scene.useRightHandedSystem = true;
  1322. GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, gltfRuntime => {
  1323. // Load runtime extensios
  1324. GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, () => {
  1325. // Create nodes
  1326. this._createNodes(gltfRuntime);
  1327. // Load buffers, shaders, materials, etc.
  1328. this._loadBuffersAsync(gltfRuntime, () => {
  1329. this._loadShadersAsync(gltfRuntime, () => {
  1330. importMaterials(gltfRuntime);
  1331. postLoad(gltfRuntime);
  1332. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  1333. onSuccess();
  1334. }
  1335. });
  1336. });
  1337. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  1338. onSuccess();
  1339. }
  1340. }, onError);
  1341. }, onError);
  1342. }
  1343. private _loadShadersAsync(gltfRuntime: IGLTFRuntime, onload: () => void): void {
  1344. var hasShaders = false;
  1345. var processShader = (sha: string, shader: IGLTFShader) => {
  1346. GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, shaderString => {
  1347. gltfRuntime.loadedShaderCount++;
  1348. if (shaderString) {
  1349. Effect.ShadersStore[sha + (shader.type === EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1350. }
  1351. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1352. onload();
  1353. }
  1354. }, () => {
  1355. Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1356. });
  1357. };
  1358. for (var sha in gltfRuntime.shaders) {
  1359. hasShaders = true;
  1360. var shader: IGLTFShader = gltfRuntime.shaders[sha];
  1361. if (shader) {
  1362. processShader.bind(this, sha, shader)();
  1363. }
  1364. else {
  1365. Tools.Error("No shader named: " + sha);
  1366. }
  1367. }
  1368. if (!hasShaders) {
  1369. onload();
  1370. }
  1371. };
  1372. private _loadBuffersAsync(gltfRuntime: IGLTFRuntime, onLoad: () => void, onProgress?: (event: ProgressEvent) => void): void {
  1373. var hasBuffers = false;
  1374. var processBuffer = (buf: string, buffer: IGLTFBuffer) => {
  1375. GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, bufferView => {
  1376. gltfRuntime.loadedBufferCount++;
  1377. if (bufferView) {
  1378. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1379. Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1380. }
  1381. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1382. }
  1383. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1384. onLoad();
  1385. }
  1386. }, () => {
  1387. Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1388. });
  1389. };
  1390. for (var buf in gltfRuntime.buffers) {
  1391. hasBuffers = true;
  1392. var buffer: IGLTFBuffer = gltfRuntime.buffers[buf];
  1393. if (buffer) {
  1394. processBuffer.bind(this, buf, buffer)();
  1395. }
  1396. else {
  1397. Tools.Error("No buffer named: " + buf);
  1398. }
  1399. }
  1400. if (!hasBuffers) {
  1401. onLoad();
  1402. }
  1403. }
  1404. private _createNodes(gltfRuntime: IGLTFRuntime): void {
  1405. var currentScene = <IGLTFScene>gltfRuntime.currentScene;
  1406. if (currentScene) {
  1407. // Only one scene even if multiple scenes are defined
  1408. for (var i = 0; i < currentScene.nodes.length; i++) {
  1409. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1410. }
  1411. }
  1412. else {
  1413. // Load all scenes
  1414. for (var thing in gltfRuntime.scenes) {
  1415. currentScene = <IGLTFScene>gltfRuntime.scenes[thing];
  1416. for (var i = 0; i < currentScene.nodes.length; i++) {
  1417. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1418. }
  1419. }
  1420. }
  1421. }
  1422. };
  1423. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = () => new GLTFLoader();
  1424. }