babylon.glTFFileLoader.js 70 KB

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