babylon.glTFFileLoader.ts 71 KB

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