babylon.glTFFileLoader.js 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957
  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. })(BABYLON || (BABYLON = {}));
  91. var BABYLON;
  92. (function (BABYLON) {
  93. /**
  94. * Tokenizer. Used for shaders compatibility
  95. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  96. */
  97. var ETokenType;
  98. (function (ETokenType) {
  99. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  100. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  101. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  102. })(ETokenType || (ETokenType = {}));
  103. var Tokenizer = (function () {
  104. function Tokenizer(toParse) {
  105. this._pos = 0;
  106. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  107. this._toParse = toParse;
  108. this._maxPos = toParse.length;
  109. }
  110. Tokenizer.prototype.getNextToken = function () {
  111. if (this.isEnd())
  112. return ETokenType.END_OF_INPUT;
  113. this.currentString = this.read();
  114. this.currentToken = ETokenType.UNKNOWN;
  115. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  116. this.currentToken = ETokenType.IDENTIFIER;
  117. this.currentIdentifier = this.currentString;
  118. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  119. this.currentIdentifier += this.currentString;
  120. this.forward();
  121. }
  122. }
  123. return this.currentToken;
  124. };
  125. Tokenizer.prototype.peek = function () {
  126. return this._toParse[this._pos];
  127. };
  128. Tokenizer.prototype.read = function () {
  129. return this._toParse[this._pos++];
  130. };
  131. Tokenizer.prototype.forward = function () {
  132. this._pos++;
  133. };
  134. Tokenizer.prototype.isEnd = function () {
  135. return this._pos >= this._maxPos;
  136. };
  137. return Tokenizer;
  138. }());
  139. /**
  140. * Values
  141. */
  142. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  143. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  144. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  145. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  146. /**
  147. * Parse
  148. */
  149. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  150. for (var buf in parsedBuffers) {
  151. var parsedBuffer = parsedBuffers[buf];
  152. gltfRuntime.buffers[buf] = parsedBuffer;
  153. gltfRuntime.buffersCount++;
  154. }
  155. };
  156. var parseShaders = function (parsedShaders, gltfRuntime) {
  157. for (var sha in parsedShaders) {
  158. var parsedShader = parsedShaders[sha];
  159. gltfRuntime.shaders[sha] = parsedShader;
  160. gltfRuntime.shaderscount++;
  161. }
  162. };
  163. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  164. for (var object in parsedObjects) {
  165. var parsedObject = parsedObjects[object];
  166. gltfRuntime[runtimeProperty][object] = parsedObject;
  167. }
  168. };
  169. /**
  170. * Utils
  171. */
  172. var normalizeUVs = function (buffer) {
  173. if (!buffer) {
  174. return;
  175. }
  176. for (var i = 0; i < buffer.length / 2; i++) {
  177. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  178. }
  179. };
  180. var replaceInString = function (str, searchValue, replaceValue) {
  181. while (str.indexOf(searchValue) !== -1) {
  182. str = str.replace(searchValue, replaceValue);
  183. }
  184. return str;
  185. };
  186. var getAttribute = function (attributeParameter) {
  187. if (attributeParameter.semantic === "NORMAL") {
  188. return "normal";
  189. }
  190. else if (attributeParameter.semantic === "POSITION") {
  191. return "position";
  192. }
  193. else if (attributeParameter.semantic === "JOINT") {
  194. return "matricesIndices";
  195. }
  196. else if (attributeParameter.semantic === "WEIGHT") {
  197. return "matricesWeights";
  198. }
  199. else if (attributeParameter.semantic === "COLOR") {
  200. return "color";
  201. }
  202. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  203. var channel = Number(attributeParameter.semantic.split("_")[1]);
  204. return "uv" + (channel === 0 ? "" : channel + 1);
  205. }
  206. };
  207. /**
  208. * Returns the animation path (glTF -> Babylon)
  209. */
  210. var getAnimationPath = function (path) {
  211. var index = glTFAnimationPaths.indexOf(path);
  212. if (index !== -1) {
  213. return babylonAnimationPaths[index];
  214. }
  215. return path;
  216. };
  217. /**
  218. * Loads and creates animations
  219. */
  220. var loadAnimations = function (gltfRuntime) {
  221. for (var anim in gltfRuntime.animations) {
  222. var animation = gltfRuntime.animations[anim];
  223. var lastAnimation = null;
  224. for (var i = 0; i < animation.channels.length; i++) {
  225. // Get parameters and load buffers
  226. var channel = animation.channels[i];
  227. var sampler = animation.samplers[channel.sampler];
  228. if (!sampler) {
  229. continue;
  230. }
  231. var inputData = animation.parameters[sampler.input];
  232. var outputData = animation.parameters[sampler.output];
  233. var bufferInput = BABYLON.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  234. var bufferOutput = BABYLON.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  235. var targetID = channel.target.id;
  236. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  237. if (targetNode === null) {
  238. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  239. continue;
  240. }
  241. var isBone = targetNode instanceof BABYLON.Bone;
  242. // Get target path (position, rotation or scaling)
  243. var targetPath = channel.target.path;
  244. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  245. if (targetPathIndex !== -1) {
  246. targetPath = babylonAnimationPaths[targetPathIndex];
  247. }
  248. // Determine animation type
  249. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  250. if (!isBone) {
  251. if (targetPath === "rotationQuaternion") {
  252. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  253. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  254. }
  255. else {
  256. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  257. }
  258. }
  259. // Create animation and key frames
  260. var babylonAnimation = null;
  261. var keys = [];
  262. var arrayOffset = 0;
  263. var modifyKey = false;
  264. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  265. babylonAnimation = lastAnimation;
  266. modifyKey = true;
  267. }
  268. if (!modifyKey) {
  269. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  270. }
  271. // For each frame
  272. for (var j = 0; j < bufferInput.length; j++) {
  273. var value = null;
  274. if (targetPath === "rotationQuaternion") {
  275. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  276. arrayOffset += 4;
  277. }
  278. else {
  279. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  280. arrayOffset += 3;
  281. }
  282. if (isBone) {
  283. var bone = targetNode;
  284. var translation = BABYLON.Vector3.Zero();
  285. var rotationQuaternion = new BABYLON.Quaternion();
  286. var scaling = BABYLON.Vector3.Zero();
  287. // Warning on decompose
  288. var mat = bone.getBaseMatrix();
  289. if (modifyKey) {
  290. mat = lastAnimation.getKeys()[j].value;
  291. }
  292. mat.decompose(scaling, rotationQuaternion, translation);
  293. if (targetPath === "position") {
  294. translation = value;
  295. }
  296. else if (targetPath === "rotationQuaternion") {
  297. rotationQuaternion = value;
  298. // Y is Up
  299. if (GLTFFileLoader.MakeYUP) {
  300. rotationQuaternion = rotationQuaternion.multiply(new BABYLON.Quaternion(-0.707107, 0, 0, 0.707107));
  301. }
  302. }
  303. else {
  304. scaling = value;
  305. }
  306. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  307. }
  308. if (!modifyKey) {
  309. keys.push({
  310. frame: bufferInput[j],
  311. value: value
  312. });
  313. }
  314. else {
  315. lastAnimation.getKeys()[j].value = value;
  316. }
  317. }
  318. // Finish
  319. if (!modifyKey) {
  320. babylonAnimation.setKeys(keys);
  321. targetNode.animations.push(babylonAnimation);
  322. }
  323. lastAnimation = babylonAnimation;
  324. gltfRuntime.scene.stopAnimation(targetNode);
  325. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  326. }
  327. }
  328. };
  329. /**
  330. * Returns the bones transformation matrix
  331. */
  332. var configureBoneTransformation = function (node) {
  333. var mat = null;
  334. if (node.translation && node.rotation && node.scale) {
  335. var scale = BABYLON.Vector3.FromArray(node.scale);
  336. var rotation = BABYLON.Quaternion.FromArray(node.rotation);
  337. var position = BABYLON.Vector3.FromArray(node.translation);
  338. // Y is Up
  339. if (GLTFFileLoader.MakeYUP) {
  340. rotation = rotation.multiply(new BABYLON.Quaternion(-0.707107, 0, 0, 0.707107));
  341. }
  342. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  343. }
  344. else {
  345. mat = BABYLON.Matrix.FromArray(node.matrix);
  346. }
  347. return mat;
  348. };
  349. /**
  350. * Returns the parent bone
  351. */
  352. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  353. // Try to find
  354. for (var i = 0; i < newSkeleton.bones.length; i++) {
  355. if (newSkeleton.bones[i].id === jointName) {
  356. return newSkeleton.bones[i];
  357. }
  358. }
  359. // Not found, search in gltf nodes
  360. var nodes = gltfRuntime.nodes;
  361. for (var nde in nodes) {
  362. var node = nodes[nde];
  363. if (!node.jointName) {
  364. continue;
  365. }
  366. var children = node.children;
  367. for (var i = 0; i < children.length; i++) {
  368. var child = gltfRuntime.nodes[children[i]];
  369. if (!child.jointName) {
  370. continue;
  371. }
  372. if (child.jointName === jointName) {
  373. var mat = configureBoneTransformation(node);
  374. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  375. bone.id = nde;
  376. return bone;
  377. }
  378. }
  379. }
  380. return null;
  381. };
  382. /**
  383. * Returns the appropriate root node
  384. */
  385. var getNodeToRoot = function (nodesToRoot, id) {
  386. for (var i = 0; i < nodesToRoot.length; i++) {
  387. var nodeToRoot = nodesToRoot[i];
  388. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  389. var child = nodeToRoot.node.children[j];
  390. if (child === id) {
  391. return nodeToRoot.bone;
  392. }
  393. }
  394. }
  395. return null;
  396. };
  397. /**
  398. * Returns the node with the joint name
  399. */
  400. var getJointNode = function (gltfRuntime, jointName) {
  401. var nodes = gltfRuntime.nodes;
  402. var node = nodes[jointName];
  403. if (node) {
  404. return {
  405. node: node,
  406. id: jointName
  407. };
  408. }
  409. for (var nde in nodes) {
  410. node = nodes[nde];
  411. if (node.jointName === jointName) {
  412. return {
  413. node: node,
  414. id: nde
  415. };
  416. }
  417. }
  418. return null;
  419. };
  420. /**
  421. * Checks if a nodes is in joints
  422. */
  423. var nodeIsInJoints = function (skins, id) {
  424. for (var i = 0; i < skins.jointNames.length; i++) {
  425. if (skins.jointNames[i] === id) {
  426. return true;
  427. }
  428. }
  429. return false;
  430. };
  431. /**
  432. * Fills the nodes to root for bones and builds hierarchy
  433. */
  434. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  435. // Creates nodes for root
  436. for (var nde in gltfRuntime.nodes) {
  437. var node = gltfRuntime.nodes[nde];
  438. var id = nde;
  439. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  440. continue;
  441. }
  442. // Create node to root bone
  443. var mat = configureBoneTransformation(node);
  444. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  445. bone.id = id;
  446. nodesToRoot.push({ bone: bone, node: node, id: id });
  447. }
  448. // Parenting
  449. for (var i = 0; i < nodesToRoot.length; i++) {
  450. var nodeToRoot = nodesToRoot[i];
  451. var children = nodeToRoot.node.children;
  452. for (var j = 0; j < children.length; j++) {
  453. var child = null;
  454. for (var k = 0; k < nodesToRoot.length; k++) {
  455. if (nodesToRoot[k].id === children[j]) {
  456. child = nodesToRoot[k];
  457. break;
  458. }
  459. }
  460. if (child) {
  461. child.bone._parent = nodeToRoot.bone;
  462. nodeToRoot.bone.children.push(child.bone);
  463. }
  464. }
  465. }
  466. };
  467. var printMat = function (m) {
  468. console.log(m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  469. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  470. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  471. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n");
  472. };
  473. /**
  474. * Imports a skeleton
  475. */
  476. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  477. if (!newSkeleton) {
  478. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  479. }
  480. if (!skins.babylonSkeleton) {
  481. return newSkeleton;
  482. }
  483. // Matrices
  484. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  485. var buffer = BABYLON.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  486. var bindShapeMatrix = BABYLON.Matrix.FromArray(skins.bindShapeMatrix);
  487. // Find the root bones
  488. var nodesToRoot = [];
  489. var nodesToRootToAdd = [];
  490. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  491. newSkeleton.bones = [];
  492. if (nodesToRoot.length === 0) {
  493. newSkeleton.needInitialSkinMatrix = true;
  494. }
  495. // Joints
  496. for (var i = 0; i < skins.jointNames.length; i++) {
  497. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  498. var node = jointNode.node;
  499. if (!node) {
  500. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  501. continue;
  502. }
  503. var id = jointNode.id;
  504. // Optimize, if the bone already exists...
  505. var existingBone = gltfRuntime.scene.getBoneByID(id);
  506. if (existingBone) {
  507. newSkeleton.bones.push(existingBone);
  508. continue;
  509. }
  510. // Check if node already exists
  511. var foundBone = false;
  512. for (var j = 0; j < newSkeleton.bones.length; j++) {
  513. if (newSkeleton.bones[j].id === id) {
  514. foundBone = true;
  515. break;
  516. }
  517. }
  518. if (foundBone) {
  519. continue;
  520. }
  521. // Search for parent bone
  522. var parentBone = null;
  523. for (var j = 0; j < i; j++) {
  524. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  525. if (!joint) {
  526. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  527. continue;
  528. }
  529. var children = joint.children;
  530. foundBone = false;
  531. for (var k = 0; k < children.length; k++) {
  532. if (children[k] === id) {
  533. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  534. foundBone = true;
  535. break;
  536. }
  537. }
  538. if (foundBone) {
  539. break;
  540. }
  541. }
  542. // Create bone
  543. var mat = configureBoneTransformation(node);
  544. if (!parentBone && nodesToRoot.length > 0) {
  545. parentBone = getNodeToRoot(nodesToRoot, id);
  546. if (parentBone) {
  547. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  548. nodesToRootToAdd.push(parentBone);
  549. }
  550. }
  551. }
  552. if (!parentBone && nodesToRoot.length === 0) {
  553. var inverseBindMatrix = BABYLON.Matrix.FromArray(buffer, i * 16);
  554. var invertMesh = BABYLON.Matrix.Invert(mesh.getWorldMatrix());
  555. mat = mat.multiply(mesh.getWorldMatrix());
  556. }
  557. var bone = new BABYLON.Bone(node.name, newSkeleton, parentBone, mat);
  558. bone.id = id;
  559. }
  560. // Polish
  561. var bones = newSkeleton.bones;
  562. newSkeleton.bones = [];
  563. for (var i = 0; i < skins.jointNames.length; i++) {
  564. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  565. if (!jointNode) {
  566. continue;
  567. }
  568. for (var j = 0; j < bones.length; j++) {
  569. if (bones[j].id === jointNode.id) {
  570. newSkeleton.bones.push(bones[j]);
  571. break;
  572. }
  573. }
  574. }
  575. // Finish
  576. newSkeleton.prepare();
  577. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  578. newSkeleton.bones.push(nodesToRootToAdd[i]);
  579. }
  580. return newSkeleton;
  581. };
  582. /**
  583. * Imports a mesh and its geometries
  584. */
  585. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  586. if (!newMesh) {
  587. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  588. newMesh.id = id;
  589. }
  590. if (!node.babylonNode) {
  591. return newMesh;
  592. }
  593. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  594. newMesh.material = multiMat;
  595. var vertexData = new BABYLON.VertexData();
  596. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  597. var verticesStarts = [];
  598. var verticesCounts = [];
  599. var indexStarts = [];
  600. var indexCounts = [];
  601. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  602. var meshID = meshes[meshIndex];
  603. var mesh = gltfRuntime.meshes[meshID];
  604. if (!mesh) {
  605. continue;
  606. }
  607. // Positions, normals and UVs
  608. for (var i = 0; i < mesh.primitives.length; i++) {
  609. // Temporary vertex data
  610. var tempVertexData = new BABYLON.VertexData();
  611. var primitive = mesh.primitives[i];
  612. if (primitive.mode !== 4) {
  613. }
  614. var attributes = primitive.attributes;
  615. var accessor = null;
  616. var buffer = null;
  617. // Set positions, normal and uvs
  618. for (var semantic in attributes) {
  619. // Link accessor and buffer view
  620. accessor = gltfRuntime.accessors[attributes[semantic]];
  621. buffer = BABYLON.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  622. if (semantic === "NORMAL") {
  623. tempVertexData.normals = new Float32Array(buffer.length);
  624. tempVertexData.normals.set(buffer);
  625. }
  626. else if (semantic === "POSITION") {
  627. if (GLTFFileLoader.HomogeneousCoordinates) {
  628. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  629. for (var j = 0; j < buffer.length; j += 4) {
  630. tempVertexData.positions[j] = buffer[j];
  631. tempVertexData.positions[j + 1] = buffer[j + 1];
  632. tempVertexData.positions[j + 2] = buffer[j + 2];
  633. }
  634. }
  635. else {
  636. tempVertexData.positions = new Float32Array(buffer.length);
  637. tempVertexData.positions.set(buffer);
  638. }
  639. verticesCounts.push(tempVertexData.positions.length);
  640. }
  641. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  642. var channel = Number(semantic.split("_")[1]);
  643. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  644. var uvs = new Float32Array(buffer.length);
  645. uvs.set(buffer);
  646. normalizeUVs(uvs);
  647. tempVertexData.set(uvs, uvKind);
  648. }
  649. else if (semantic === "JOINT") {
  650. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  651. tempVertexData.matricesIndices.set(buffer);
  652. }
  653. else if (semantic === "WEIGHT") {
  654. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  655. tempVertexData.matricesWeights.set(buffer);
  656. }
  657. else if (semantic === "COLOR") {
  658. tempVertexData.colors = new Float32Array(buffer.length);
  659. tempVertexData.colors.set(buffer);
  660. }
  661. }
  662. // Indices
  663. accessor = gltfRuntime.accessors[primitive.indices];
  664. buffer = BABYLON.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  665. tempVertexData.indices = new Int32Array(buffer.length);
  666. tempVertexData.indices.set(buffer);
  667. indexCounts.push(tempVertexData.indices.length);
  668. vertexData.merge(tempVertexData);
  669. tempVertexData = undefined;
  670. // Sub material
  671. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  672. multiMat.subMaterials.push(material === null ? gltfRuntime.scene.defaultMaterial : material);
  673. // Update vertices start and index start
  674. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  675. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  676. }
  677. }
  678. // Apply geometry
  679. geometry.setAllVerticesData(vertexData, false);
  680. newMesh.computeWorldMatrix(true);
  681. // Apply submeshes
  682. newMesh.subMeshes = [];
  683. var index = 0;
  684. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  685. var meshID = meshes[meshIndex];
  686. var mesh = gltfRuntime.meshes[meshID];
  687. if (!mesh) {
  688. continue;
  689. }
  690. for (var i = 0; i < mesh.primitives.length; i++) {
  691. if (mesh.primitives[i].mode !== 4) {
  692. }
  693. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  694. index++;
  695. }
  696. }
  697. // Finish
  698. return newMesh;
  699. };
  700. /**
  701. * Configure node transformation from position, rotation and scaling
  702. */
  703. var configureNode = function (newNode, position, rotation, scaling) {
  704. if (newNode.position) {
  705. newNode.position = position;
  706. }
  707. if (newNode.rotationQuaternion || newNode.rotation) {
  708. newNode.rotationQuaternion = rotation;
  709. }
  710. if (newNode.scaling) {
  711. newNode.scaling = scaling;
  712. }
  713. };
  714. /**
  715. * Configures node from transformation matrix
  716. */
  717. var configureNodeFromMatrix = function (newNode, node) {
  718. if (node.matrix) {
  719. var position = new BABYLON.Vector3(0, 0, 0);
  720. var rotation = new BABYLON.Quaternion();
  721. var scaling = new BABYLON.Vector3(0, 0, 0);
  722. var mat = BABYLON.Matrix.FromArray(node.matrix);
  723. mat.decompose(scaling, rotation, position);
  724. // Y is Up
  725. if (GLTFFileLoader.MakeYUP) {
  726. rotation = rotation.multiply(new BABYLON.Quaternion(-0.707107, 0, 0, 0.707107));
  727. }
  728. configureNode(newNode, position, rotation, scaling);
  729. if (newNode instanceof BABYLON.TargetCamera) {
  730. newNode.setTarget(BABYLON.Vector3.Zero());
  731. }
  732. }
  733. else {
  734. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  735. }
  736. };
  737. /**
  738. * Imports a node
  739. */
  740. var importNode = function (gltfRuntime, node, id) {
  741. var lastNode = null;
  742. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  743. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  744. return null;
  745. }
  746. }
  747. // Meshes
  748. if (node.skin) {
  749. if (node.meshes) {
  750. var skin = gltfRuntime.skins[node.skin];
  751. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  752. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  753. if (newMesh.skeleton === null) {
  754. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  755. if (!skin.babylonSkeleton) {
  756. skin.babylonSkeleton = newMesh.skeleton;
  757. }
  758. }
  759. if (newMesh.skeleton !== null) {
  760. newMesh.useBones = true;
  761. }
  762. lastNode = newMesh;
  763. }
  764. }
  765. else if (node.meshes) {
  766. /**
  767. * Improve meshes property
  768. */
  769. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  770. lastNode = newMesh;
  771. }
  772. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  773. var light = gltfRuntime.lights[node.light];
  774. if (light) {
  775. if (light.type === "ambient") {
  776. var ambienLight = light[light.type];
  777. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  778. hemiLight.name = node.name;
  779. if (ambienLight.color) {
  780. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  781. }
  782. lastNode = hemiLight;
  783. }
  784. else if (light.type === "directional") {
  785. var directionalLight = light[light.type];
  786. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  787. dirLight.name = node.name;
  788. if (directionalLight.color) {
  789. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  790. }
  791. lastNode = dirLight;
  792. }
  793. else if (light.type === "point") {
  794. var pointLight = light[light.type];
  795. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  796. ptLight.name = node.name;
  797. if (pointLight.color) {
  798. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  799. }
  800. lastNode = ptLight;
  801. }
  802. else if (light.type === "spot") {
  803. var spotLight = light[light.type];
  804. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  805. spLight.name = node.name;
  806. if (spotLight.color) {
  807. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  808. }
  809. if (spotLight.fallOfAngle) {
  810. spLight.angle = spotLight.fallOfAngle;
  811. }
  812. if (spotLight.fallOffExponent) {
  813. spLight.exponent = spotLight.fallOffExponent;
  814. }
  815. lastNode = spLight;
  816. }
  817. }
  818. }
  819. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  820. var camera = gltfRuntime.cameras[node.camera];
  821. if (camera) {
  822. if (camera.type === "orthographic") {
  823. var orthographicCamera = camera[camera.type];
  824. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  825. orthoCamera.name = node.name;
  826. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  827. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  828. lastNode = orthoCamera;
  829. }
  830. else if (camera.type === "perspective") {
  831. var perspectiveCamera = camera[camera.type];
  832. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  833. persCamera.name = node.name;
  834. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  835. if (!perspectiveCamera.aspectRatio) {
  836. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  837. }
  838. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  839. persCamera.maxZ = perspectiveCamera.zfar;
  840. persCamera.minZ = perspectiveCamera.znear;
  841. }
  842. lastNode = persCamera;
  843. }
  844. }
  845. }
  846. // Empty node
  847. if (!node.jointName) {
  848. if (node.babylonNode) {
  849. return node.babylonNode;
  850. }
  851. else if (lastNode === null) {
  852. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  853. node.babylonNode = dummy;
  854. lastNode = dummy;
  855. }
  856. }
  857. if (lastNode !== null) {
  858. if (node.matrix) {
  859. configureNodeFromMatrix(lastNode, node);
  860. }
  861. else {
  862. configureNode(lastNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.RotationAxis(BABYLON.Vector3.FromArray(node.rotation).normalize(), node.rotation[3]), BABYLON.Vector3.FromArray(node.scale));
  863. }
  864. lastNode.updateCache(true);
  865. node.babylonNode = lastNode;
  866. }
  867. return lastNode;
  868. };
  869. /**
  870. * Traverses nodes and creates them
  871. */
  872. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  873. var node = gltfRuntime.nodes[id];
  874. var newNode = null;
  875. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  876. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  877. meshIncluded = true;
  878. }
  879. else {
  880. meshIncluded = false;
  881. }
  882. }
  883. else {
  884. meshIncluded = true;
  885. }
  886. if (!node.jointName && meshIncluded) {
  887. newNode = importNode(gltfRuntime, node, id);
  888. if (newNode !== null) {
  889. newNode.id = id;
  890. newNode.parent = parent;
  891. }
  892. }
  893. for (var i = 0; i < node.children.length; i++) {
  894. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  895. }
  896. };
  897. /**
  898. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  899. */
  900. var postLoad = function (gltfRuntime) {
  901. // Nodes
  902. var currentScene = gltfRuntime.currentScene;
  903. for (var i = 0; i < currentScene.nodes.length; i++) {
  904. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  905. }
  906. // Set animations
  907. loadAnimations(gltfRuntime);
  908. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  909. var skeleton = gltfRuntime.scene.skeletons[i];
  910. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  911. }
  912. };
  913. /**
  914. * onBind shaderrs callback to set uniforms and matrices
  915. */
  916. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  917. for (var unif in unTreatedUniforms) {
  918. var uniform = unTreatedUniforms[unif];
  919. var type = uniform.type;
  920. if (type === BABYLON.EParameterType.FLOAT_MAT2 || type === BABYLON.EParameterType.FLOAT_MAT3 || type === BABYLON.EParameterType.FLOAT_MAT4) {
  921. if (uniform.semantic && !uniform.source && !uniform.node) {
  922. BABYLON.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  923. }
  924. else if (uniform.semantic && (uniform.source || uniform.node)) {
  925. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  926. if (source === null) {
  927. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  928. }
  929. if (source === null) {
  930. continue;
  931. }
  932. BABYLON.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  933. }
  934. }
  935. else {
  936. var value = material.values[technique.uniforms[unif]];
  937. if (!value) {
  938. continue;
  939. }
  940. if (type === BABYLON.EParameterType.SAMPLER_2D) {
  941. var texture = gltfRuntime.textures[value].babylonTexture;
  942. if (texture === null) {
  943. continue;
  944. }
  945. shaderMaterial.getEffect().setTexture(unif, texture);
  946. }
  947. else {
  948. BABYLON.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  949. }
  950. }
  951. }
  952. onSuccess(shaderMaterial);
  953. };
  954. /**
  955. * Prepare uniforms to send the only one time
  956. * Loads the appropriate textures
  957. */
  958. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  959. var materialValues = material.values;
  960. var techniqueUniforms = technique.uniforms;
  961. /**
  962. * Prepare values here (not matrices)
  963. */
  964. for (var unif in unTreatedUniforms) {
  965. var uniform = unTreatedUniforms[unif];
  966. var type = uniform.type;
  967. var value = materialValues[techniqueUniforms[unif]] || uniform.value;
  968. if (!value) {
  969. continue;
  970. }
  971. var onLoadTexture = function (texture) {
  972. if (uniform.value) {
  973. // Static uniform
  974. shaderMaterial.setTexture(unif, texture);
  975. delete unTreatedUniforms[unif];
  976. }
  977. };
  978. // Texture (sampler2D)
  979. if (type === BABYLON.EParameterType.SAMPLER_2D) {
  980. BABYLON.GLTFFileLoaderExtension.LoadTextureAsync(gltfRuntime, value, onLoadTexture, function () { return onLoadTexture(null); });
  981. }
  982. else {
  983. if (uniform.value && BABYLON.GLTFUtils.SetUniform(shaderMaterial, unif, value, type)) {
  984. // Static uniform
  985. delete unTreatedUniforms[unif];
  986. }
  987. }
  988. }
  989. };
  990. /**
  991. * Shader compilation failed
  992. */
  993. var onShaderCompileError = function (program, shaderMaterial, onError) {
  994. return function (effect, error) {
  995. BABYLON.Tools.Error("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  996. shaderMaterial.dispose(true);
  997. onError();
  998. };
  999. };
  1000. /**
  1001. * Shader compilation success
  1002. */
  1003. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1004. return function (_) {
  1005. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1006. shaderMaterial.onBind = function (mesh) {
  1007. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1008. };
  1009. };
  1010. };
  1011. /**
  1012. * Returns the appropriate uniform if already handled by babylon
  1013. */
  1014. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1015. for (var unif in technique.uniforms) {
  1016. var uniform = technique.uniforms[unif];
  1017. var uniformParameter = technique.parameters[uniform];
  1018. if (tokenizer.currentIdentifier === unif) {
  1019. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1020. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1021. if (transformIndex !== -1) {
  1022. delete unTreatedUniforms[unif];
  1023. return babylonTransforms[transformIndex];
  1024. }
  1025. }
  1026. }
  1027. }
  1028. return tokenizer.currentIdentifier;
  1029. };
  1030. /**
  1031. * All shaders loaded. Create materials one by one
  1032. */
  1033. var importMaterials = function (gltfRuntime) {
  1034. // Create materials
  1035. for (var mat in gltfRuntime.materials) {
  1036. BABYLON.GLTFFileLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1037. }
  1038. };
  1039. /**
  1040. * Implementation of the base glTF spec
  1041. */
  1042. var GLTFFileLoaderBase = (function () {
  1043. function GLTFFileLoaderBase() {
  1044. }
  1045. GLTFFileLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1046. var gltfRuntime = {
  1047. accessors: {},
  1048. buffers: {},
  1049. bufferViews: {},
  1050. meshes: {},
  1051. lights: {},
  1052. cameras: {},
  1053. nodes: {},
  1054. images: {},
  1055. textures: {},
  1056. shaders: {},
  1057. programs: {},
  1058. samplers: {},
  1059. techniques: {},
  1060. materials: {},
  1061. animations: {},
  1062. skins: {},
  1063. currentScene: {},
  1064. extensionsUsed: [],
  1065. buffersCount: 0,
  1066. shaderscount: 0,
  1067. scene: scene,
  1068. rootUrl: rootUrl,
  1069. loadedBufferCount: 0,
  1070. loadedBufferViews: {},
  1071. loadedShaderCount: 0,
  1072. importOnlyMeshes: false,
  1073. dummyNodes: []
  1074. };
  1075. // Parse
  1076. if (parsedData.extensionsUsed) {
  1077. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1078. }
  1079. if (parsedData.buffers) {
  1080. parseBuffers(parsedData.buffers, gltfRuntime);
  1081. }
  1082. if (parsedData.bufferViews) {
  1083. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1084. }
  1085. if (parsedData.accessors) {
  1086. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1087. }
  1088. if (parsedData.meshes) {
  1089. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1090. }
  1091. if (parsedData.lights) {
  1092. parseObject(parsedData.lights, "lights", gltfRuntime);
  1093. }
  1094. if (parsedData.cameras) {
  1095. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1096. }
  1097. if (parsedData.nodes) {
  1098. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1099. }
  1100. if (parsedData.images) {
  1101. parseObject(parsedData.images, "images", gltfRuntime);
  1102. }
  1103. if (parsedData.textures) {
  1104. parseObject(parsedData.textures, "textures", gltfRuntime);
  1105. }
  1106. if (parsedData.shaders) {
  1107. parseShaders(parsedData.shaders, gltfRuntime);
  1108. }
  1109. if (parsedData.programs) {
  1110. parseObject(parsedData.programs, "programs", gltfRuntime);
  1111. }
  1112. if (parsedData.samplers) {
  1113. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1114. }
  1115. if (parsedData.techniques) {
  1116. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1117. }
  1118. if (parsedData.materials) {
  1119. parseObject(parsedData.materials, "materials", gltfRuntime);
  1120. }
  1121. if (parsedData.animations) {
  1122. parseObject(parsedData.animations, "animations", gltfRuntime);
  1123. }
  1124. if (parsedData.skins) {
  1125. parseObject(parsedData.skins, "skins", gltfRuntime);
  1126. }
  1127. if (parsedData.scene && parsedData.scenes) {
  1128. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1129. }
  1130. return gltfRuntime;
  1131. };
  1132. GLTFFileLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1133. var buffer = gltfRuntime.buffers[id];
  1134. if (BABYLON.GLTFUtils.IsBase64(buffer.uri)) {
  1135. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.GLTFUtils.DecodeBase64(buffer.uri))); });
  1136. }
  1137. else {
  1138. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, onError);
  1139. }
  1140. };
  1141. GLTFFileLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1142. var texture = gltfRuntime.textures[id];
  1143. if (!texture || !texture.source) {
  1144. onError();
  1145. return;
  1146. }
  1147. if (texture.babylonTexture) {
  1148. onSuccess(null);
  1149. return;
  1150. }
  1151. var source = gltfRuntime.images[texture.source];
  1152. if (BABYLON.GLTFUtils.IsBase64(source.uri)) {
  1153. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.GLTFUtils.DecodeBase64(source.uri))); });
  1154. }
  1155. else {
  1156. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, onError);
  1157. }
  1158. };
  1159. GLTFFileLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1160. var texture = gltfRuntime.textures[id];
  1161. if (texture.babylonTexture) {
  1162. onSuccess(texture.babylonTexture);
  1163. return;
  1164. }
  1165. var sampler = gltfRuntime.samplers[texture.sampler];
  1166. var createMipMaps = (sampler.minFilter === BABYLON.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1167. (sampler.minFilter === BABYLON.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1168. (sampler.minFilter === BABYLON.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1169. (sampler.minFilter === BABYLON.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1170. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1171. var blob = new Blob([buffer]);
  1172. var blobURL = URL.createObjectURL(blob);
  1173. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1174. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1175. newTexture.wrapU = BABYLON.GLTFUtils.GetWrapMode(sampler.wrapS);
  1176. newTexture.wrapV = BABYLON.GLTFUtils.GetWrapMode(sampler.wrapT);
  1177. newTexture.name = id;
  1178. texture.babylonTexture = newTexture;
  1179. onSuccess(newTexture);
  1180. };
  1181. GLTFFileLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1182. var shader = gltfRuntime.shaders[id];
  1183. if (BABYLON.GLTFUtils.IsBase64(shader.uri)) {
  1184. var shaderString = atob(shader.uri.split(",")[1]);
  1185. onSuccess(shaderString);
  1186. }
  1187. else {
  1188. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, onError);
  1189. }
  1190. };
  1191. GLTFFileLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1192. var material = gltfRuntime.materials[id];
  1193. var technique = gltfRuntime.techniques[material.technique];
  1194. if (!technique) {
  1195. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1196. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  1197. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1198. onSuccess(defaultMaterial);
  1199. return;
  1200. }
  1201. var program = gltfRuntime.programs[technique.program];
  1202. var states = technique.states;
  1203. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1204. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1205. var newVertexShader = "";
  1206. var newPixelShader = "";
  1207. var vertexTokenizer = new Tokenizer(vertexShader);
  1208. var pixelTokenizer = new Tokenizer(pixelShader);
  1209. var unTreatedUniforms = {};
  1210. var uniforms = [];
  1211. var attributes = [];
  1212. var samplers = [];
  1213. // Fill uniform, sampler2D and attributes
  1214. for (var unif in technique.uniforms) {
  1215. var uniform = technique.uniforms[unif];
  1216. var uniformParameter = technique.parameters[uniform];
  1217. unTreatedUniforms[unif] = uniformParameter;
  1218. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1219. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1220. if (transformIndex !== -1) {
  1221. uniforms.push(babylonTransforms[transformIndex]);
  1222. delete unTreatedUniforms[unif];
  1223. }
  1224. else {
  1225. uniforms.push(unif);
  1226. }
  1227. }
  1228. else if (uniformParameter.type === BABYLON.EParameterType.SAMPLER_2D) {
  1229. samplers.push(unif);
  1230. }
  1231. else {
  1232. uniforms.push(unif);
  1233. }
  1234. }
  1235. for (var attr in technique.attributes) {
  1236. var attribute = technique.attributes[attr];
  1237. var attributeParameter = technique.parameters[attribute];
  1238. if (attributeParameter.semantic) {
  1239. attributes.push(getAttribute(attributeParameter));
  1240. }
  1241. }
  1242. // Configure vertex shader
  1243. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1244. var tokenType = vertexTokenizer.currentToken;
  1245. if (tokenType !== ETokenType.IDENTIFIER) {
  1246. newVertexShader += vertexTokenizer.currentString;
  1247. continue;
  1248. }
  1249. var foundAttribute = false;
  1250. for (var attr in technique.attributes) {
  1251. var attribute = technique.attributes[attr];
  1252. var attributeParameter = technique.parameters[attribute];
  1253. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1254. newVertexShader += getAttribute(attributeParameter);
  1255. foundAttribute = true;
  1256. break;
  1257. }
  1258. }
  1259. if (foundAttribute) {
  1260. continue;
  1261. }
  1262. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1263. }
  1264. // Configure pixel shader
  1265. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1266. var tokenType = pixelTokenizer.currentToken;
  1267. if (tokenType !== ETokenType.IDENTIFIER) {
  1268. newPixelShader += pixelTokenizer.currentString;
  1269. continue;
  1270. }
  1271. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1272. }
  1273. // Create shader material
  1274. var shaderPath = {
  1275. vertex: program.vertexShader + id,
  1276. fragment: program.fragmentShader + id
  1277. };
  1278. var options = {
  1279. attributes: attributes,
  1280. uniforms: uniforms,
  1281. samplers: samplers,
  1282. needAlphaBlending: states.functions && states.functions.blendEquationSeparate
  1283. };
  1284. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1285. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1286. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1287. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1288. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1289. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1290. if (states.functions) {
  1291. var functions = states.functions;
  1292. if (functions.cullFace && functions.cullFace[0] !== BABYLON.ECullingType.BACK) {
  1293. shaderMaterial.backFaceCulling = false;
  1294. }
  1295. var blendFunc = functions.blendFuncSeparate;
  1296. if (blendFunc) {
  1297. if (blendFunc[0] === BABYLON.EBlendingFunction.SRC_ALPHA && blendFunc[1] === BABYLON.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === BABYLON.EBlendingFunction.ONE && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1298. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1299. }
  1300. else if (blendFunc[0] === BABYLON.EBlendingFunction.ONE && blendFunc[1] === BABYLON.EBlendingFunction.ONE && blendFunc[2] === BABYLON.EBlendingFunction.ZERO && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1301. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  1302. }
  1303. else if (blendFunc[0] === BABYLON.EBlendingFunction.SRC_ALPHA && blendFunc[1] === BABYLON.EBlendingFunction.ONE && blendFunc[2] === BABYLON.EBlendingFunction.ZERO && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1304. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  1305. }
  1306. else if (blendFunc[0] === BABYLON.EBlendingFunction.ZERO && blendFunc[1] === BABYLON.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === BABYLON.EBlendingFunction.ONE && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1307. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  1308. }
  1309. else if (blendFunc[0] === BABYLON.EBlendingFunction.DST_COLOR && blendFunc[1] === BABYLON.EBlendingFunction.ZERO && blendFunc[2] === BABYLON.EBlendingFunction.ONE && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1310. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  1311. }
  1312. else if (blendFunc[0] === BABYLON.EBlendingFunction.SRC_ALPHA && blendFunc[1] === BABYLON.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === BABYLON.EBlendingFunction.ONE && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1313. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  1314. }
  1315. }
  1316. }
  1317. };
  1318. return GLTFFileLoaderBase;
  1319. }());
  1320. BABYLON.GLTFFileLoaderBase = GLTFFileLoaderBase;
  1321. /**
  1322. * glTF File Loader Plugin
  1323. */
  1324. var GLTFFileLoader = (function () {
  1325. function GLTFFileLoader() {
  1326. /**
  1327. * Public members
  1328. */
  1329. this.extensions = {
  1330. ".gltf": { isBinary: false },
  1331. ".glb": { isBinary: true }
  1332. };
  1333. }
  1334. GLTFFileLoader.RegisterExtension = function (extension) {
  1335. if (GLTFFileLoader.Extensions[extension.name]) {
  1336. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1337. return;
  1338. }
  1339. GLTFFileLoader.Extensions[extension.name] = extension;
  1340. };
  1341. /**
  1342. * Import meshes
  1343. */
  1344. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onError) {
  1345. var _this = this;
  1346. scene.useRightHandedSystem = true;
  1347. var gltfRuntime = BABYLON.GLTFFileLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1348. gltfRuntime.importOnlyMeshes = true;
  1349. if (meshesNames === "") {
  1350. gltfRuntime.importMeshesNames = [];
  1351. }
  1352. else if (typeof meshesNames === "string") {
  1353. gltfRuntime.importMeshesNames = [meshesNames];
  1354. }
  1355. else if (meshesNames && !(meshesNames instanceof Array)) {
  1356. gltfRuntime.importMeshesNames = [meshesNames];
  1357. }
  1358. else {
  1359. gltfRuntime.importMeshesNames = [];
  1360. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1361. }
  1362. // Create nodes
  1363. _this._createNodes(gltfRuntime);
  1364. var meshes = [];
  1365. var skeletons = [];
  1366. // Fill arrays of meshes and skeletons
  1367. for (var nde in gltfRuntime.nodes) {
  1368. var node = gltfRuntime.nodes[nde];
  1369. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1370. meshes.push(node.babylonNode);
  1371. }
  1372. }
  1373. for (var skl in gltfRuntime.skins) {
  1374. var skin = gltfRuntime.skins[skl];
  1375. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1376. skeletons.push(skin.babylonSkeleton);
  1377. }
  1378. }
  1379. // Load buffers, shaders, materials, etc.
  1380. _this._loadBuffersAsync(gltfRuntime, function () {
  1381. _this._loadShadersAsync(gltfRuntime, function () {
  1382. importMaterials(gltfRuntime);
  1383. postLoad(gltfRuntime);
  1384. });
  1385. });
  1386. if (onSuccess) {
  1387. onSuccess(meshes, null, skeletons);
  1388. }
  1389. }, onError);
  1390. return true;
  1391. };
  1392. /**
  1393. * Load scene
  1394. */
  1395. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1396. var _this = this;
  1397. scene.useRightHandedSystem = true;
  1398. BABYLON.GLTFFileLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1399. // Create nodes
  1400. _this._createNodes(gltfRuntime);
  1401. // Load buffers, shaders, materials, etc.
  1402. _this._loadBuffersAsync(gltfRuntime, function () {
  1403. _this._loadShadersAsync(gltfRuntime, function () {
  1404. importMaterials(gltfRuntime);
  1405. postLoad(gltfRuntime);
  1406. });
  1407. });
  1408. onSuccess();
  1409. }, onError);
  1410. return true;
  1411. };
  1412. GLTFFileLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1413. var hasShaders = false;
  1414. var processShader = function (sha, shader) {
  1415. BABYLON.GLTFFileLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1416. gltfRuntime.loadedShaderCount++;
  1417. if (shaderString) {
  1418. BABYLON.Effect.ShadersStore[sha + (shader.type === BABYLON.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1419. }
  1420. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1421. onload();
  1422. }
  1423. }, function () {
  1424. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1425. });
  1426. };
  1427. for (var sha in gltfRuntime.shaders) {
  1428. hasShaders = true;
  1429. var shader = gltfRuntime.shaders[sha];
  1430. if (shader) {
  1431. processShader.bind(this, sha, shader)();
  1432. }
  1433. else {
  1434. BABYLON.Tools.Error("No shader named: " + sha);
  1435. }
  1436. }
  1437. if (!hasShaders) {
  1438. onload();
  1439. }
  1440. };
  1441. ;
  1442. GLTFFileLoader.prototype._loadBuffersAsync = function (gltfRuntime, onload) {
  1443. var hasBuffers = false;
  1444. var processBuffer = function (buf, buffer) {
  1445. BABYLON.GLTFFileLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  1446. gltfRuntime.loadedBufferCount++;
  1447. if (bufferView) {
  1448. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1449. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1450. }
  1451. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1452. }
  1453. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1454. onload();
  1455. }
  1456. }, function () {
  1457. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1458. });
  1459. };
  1460. for (var buf in gltfRuntime.buffers) {
  1461. hasBuffers = true;
  1462. var buffer = gltfRuntime.buffers[buf];
  1463. if (buffer) {
  1464. processBuffer.bind(this, buf, buffer)();
  1465. }
  1466. else {
  1467. BABYLON.Tools.Error("No buffer named: " + buf);
  1468. }
  1469. }
  1470. if (!hasBuffers) {
  1471. onload();
  1472. }
  1473. };
  1474. // Creates nodes before loading buffers and shaders
  1475. GLTFFileLoader.prototype._createNodes = function (gltfRuntime) {
  1476. var currentScene = gltfRuntime.currentScene;
  1477. for (var i = 0; i < currentScene.nodes.length; i++) {
  1478. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1479. }
  1480. };
  1481. /**
  1482. * Private members
  1483. */
  1484. // None
  1485. /**
  1486. * Static members
  1487. */
  1488. GLTFFileLoader.MakeYUP = false;
  1489. GLTFFileLoader.HomogeneousCoordinates = false;
  1490. GLTFFileLoader.Extensions = {};
  1491. return GLTFFileLoader;
  1492. }());
  1493. BABYLON.GLTFFileLoader = GLTFFileLoader;
  1494. ;
  1495. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  1496. })(BABYLON || (BABYLON = {}));
  1497. var BABYLON;
  1498. (function (BABYLON) {
  1499. /**
  1500. * Utils functions for GLTF
  1501. */
  1502. var GLTFUtils = (function () {
  1503. function GLTFUtils() {
  1504. }
  1505. /**
  1506. * Sets the given "parameter" matrix
  1507. * @param scene: the {BABYLON.Scene} object
  1508. * @param source: the source node where to pick the matrix
  1509. * @param parameter: the GLTF technique parameter
  1510. * @param uniformName: the name of the shader's uniform
  1511. * @param shaderMaterial: the shader material
  1512. */
  1513. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  1514. var mat = null;
  1515. if (parameter.semantic === "MODEL") {
  1516. mat = source.getWorldMatrix();
  1517. }
  1518. else if (parameter.semantic === "PROJECTION") {
  1519. mat = scene.getProjectionMatrix();
  1520. }
  1521. else if (parameter.semantic === "VIEW") {
  1522. mat = scene.getViewMatrix();
  1523. }
  1524. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  1525. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  1526. }
  1527. else if (parameter.semantic === "MODELVIEW") {
  1528. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  1529. }
  1530. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  1531. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  1532. }
  1533. else if (parameter.semantic === "MODELINVERSE") {
  1534. mat = source.getWorldMatrix().invert();
  1535. }
  1536. else if (parameter.semantic === "VIEWINVERSE") {
  1537. mat = scene.getViewMatrix().invert();
  1538. }
  1539. else if (parameter.semantic === "PROJECTIONINVERSE") {
  1540. mat = scene.getProjectionMatrix().invert();
  1541. }
  1542. else if (parameter.semantic === "MODELVIEWINVERSE") {
  1543. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  1544. }
  1545. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  1546. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  1547. }
  1548. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  1549. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  1550. }
  1551. else {
  1552. debugger;
  1553. }
  1554. switch (parameter.type) {
  1555. case BABYLON.EParameterType.FLOAT_MAT2:
  1556. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  1557. break;
  1558. case BABYLON.EParameterType.FLOAT_MAT3:
  1559. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  1560. break;
  1561. case BABYLON.EParameterType.FLOAT_MAT4:
  1562. shaderMaterial.setMatrix(uniformName, mat);
  1563. break;
  1564. default: break;
  1565. }
  1566. };
  1567. /**
  1568. * Sets the given "parameter" matrix
  1569. * @param shaderMaterial: the shader material
  1570. * @param uniform: the name of the shader's uniform
  1571. * @param value: the value of the uniform
  1572. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  1573. */
  1574. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  1575. switch (type) {
  1576. case BABYLON.EParameterType.FLOAT:
  1577. shaderMaterial.setFloat(uniform, value);
  1578. return true;
  1579. case BABYLON.EParameterType.FLOAT_VEC2:
  1580. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  1581. return true;
  1582. case BABYLON.EParameterType.FLOAT_VEC3:
  1583. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  1584. return true;
  1585. case BABYLON.EParameterType.FLOAT_VEC4:
  1586. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  1587. return true;
  1588. default: return false;
  1589. }
  1590. };
  1591. /**
  1592. * If the uri is a base64 string
  1593. * @param uri: the uri to test
  1594. */
  1595. GLTFUtils.IsBase64 = function (uri) {
  1596. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1597. };
  1598. /**
  1599. * Decode the base64 uri
  1600. * @param uri: the uri to decode
  1601. */
  1602. GLTFUtils.DecodeBase64 = function (uri) {
  1603. var decodedString = atob(uri.split(",")[1]);
  1604. var bufferLength = decodedString.length;
  1605. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1606. for (var i = 0; i < bufferLength; i++) {
  1607. bufferView[i] = decodedString.charCodeAt(i);
  1608. }
  1609. return bufferView.buffer;
  1610. };
  1611. /**
  1612. * Returns the wrap mode of the texture
  1613. * @param mode: the mode value
  1614. */
  1615. GLTFUtils.GetWrapMode = function (mode) {
  1616. switch (mode) {
  1617. case BABYLON.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1618. case BABYLON.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1619. case BABYLON.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1620. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1621. }
  1622. };
  1623. /**
  1624. * Returns the byte stride giving an accessor
  1625. * @param accessor: the GLTF accessor objet
  1626. */
  1627. GLTFUtils.GetByteStrideFromType = function (accessor) {
  1628. // Needs this function since "byteStride" isn't requiered in glTF format
  1629. var type = accessor.type;
  1630. switch (type) {
  1631. case "VEC2": return 2;
  1632. case "VEC3": return 3;
  1633. case "VEC4": return 4;
  1634. case "MAT2": return 4;
  1635. case "MAT3": return 9;
  1636. case "MAT4": return 16;
  1637. default: return 1;
  1638. }
  1639. };
  1640. /**
  1641. * Returns the texture filter mode giving a mode value
  1642. * @param mode: the filter mode value
  1643. */
  1644. GLTFUtils.GetTextureFilterMode = function (mode) {
  1645. switch (mode) {
  1646. case BABYLON.ETextureFilterType.LINEAR:
  1647. case BABYLON.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  1648. case BABYLON.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1649. case BABYLON.ETextureFilterType.NEAREST:
  1650. case BABYLON.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1651. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1652. }
  1653. };
  1654. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  1655. var byteOffset = bufferView.byteOffset + byteOffset;
  1656. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  1657. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  1658. throw new Error("Buffer access is out of range");
  1659. }
  1660. var buffer = loadedBufferView.buffer;
  1661. byteOffset += loadedBufferView.byteOffset;
  1662. switch (componentType) {
  1663. case BABYLON.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  1664. case BABYLON.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  1665. case BABYLON.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  1666. case BABYLON.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  1667. default: return new Float32Array(buffer, byteOffset, byteLength);
  1668. }
  1669. };
  1670. /**
  1671. * Returns a buffer from its accessor
  1672. * @param gltfRuntime: the GLTF runtime
  1673. * @param accessor: the GLTF accessor
  1674. */
  1675. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  1676. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  1677. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  1678. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  1679. };
  1680. /**
  1681. * Decodes a buffer view into a string
  1682. * @param view: the buffer view
  1683. */
  1684. GLTFUtils.DecodeBufferToText = function (view) {
  1685. var result = "";
  1686. var length = view.byteLength;
  1687. for (var i = 0; i < length; ++i) {
  1688. result += String.fromCharCode(view[i]);
  1689. }
  1690. return result;
  1691. };
  1692. return GLTFUtils;
  1693. }());
  1694. BABYLON.GLTFUtils = GLTFUtils;
  1695. })(BABYLON || (BABYLON = {}));
  1696. var BABYLON;
  1697. (function (BABYLON) {
  1698. var GLTFFileLoaderExtension = (function () {
  1699. function GLTFFileLoaderExtension(name) {
  1700. this._name = name;
  1701. }
  1702. Object.defineProperty(GLTFFileLoaderExtension.prototype, "name", {
  1703. get: function () {
  1704. return this._name;
  1705. },
  1706. enumerable: true,
  1707. configurable: true
  1708. });
  1709. /**
  1710. * Defines an override for loading the runtime
  1711. * Return true to stop further extensions from loading the runtime
  1712. */
  1713. GLTFFileLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1714. return false;
  1715. };
  1716. /**
  1717. * Defines an override for loading buffers
  1718. * Return true to stop further extensions from loading this buffer
  1719. */
  1720. GLTFFileLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1721. return false;
  1722. };
  1723. /**
  1724. * Defines an override for loading texture buffers
  1725. * Return true to stop further extensions from loading this texture data
  1726. */
  1727. GLTFFileLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1728. return false;
  1729. };
  1730. /**
  1731. * Defines an override for creating textures
  1732. * Return true to stop further extensions from loading this texture
  1733. */
  1734. GLTFFileLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1735. return false;
  1736. };
  1737. /**
  1738. * Defines an override for loading shader strings
  1739. * Return true to stop further extensions from loading this shader data
  1740. */
  1741. GLTFFileLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1742. return false;
  1743. };
  1744. /**
  1745. * Defines an override for loading materials
  1746. * Return true to stop further extensions from loading this material
  1747. */
  1748. GLTFFileLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1749. return false;
  1750. };
  1751. // ---------
  1752. // Utilities
  1753. // ---------
  1754. GLTFFileLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1755. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1756. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  1757. }, function () {
  1758. setTimeout(function () {
  1759. onSuccess(BABYLON.GLTFFileLoaderBase.CreateRuntime(JSON.parse(data), scene, rootUrl));
  1760. });
  1761. });
  1762. };
  1763. GLTFFileLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1764. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1765. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError);
  1766. }, function () {
  1767. BABYLON.GLTFFileLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError);
  1768. });
  1769. };
  1770. GLTFFileLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  1771. GLTFFileLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFFileLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  1772. };
  1773. GLTFFileLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1774. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1775. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  1776. }, function () {
  1777. BABYLON.GLTFFileLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  1778. });
  1779. };
  1780. GLTFFileLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1781. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1782. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  1783. }, function () {
  1784. BABYLON.GLTFFileLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  1785. });
  1786. };
  1787. GLTFFileLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1788. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1789. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  1790. }, function () {
  1791. BABYLON.GLTFFileLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  1792. });
  1793. };
  1794. GLTFFileLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1795. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1796. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1797. }, function () {
  1798. BABYLON.GLTFFileLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1799. });
  1800. };
  1801. GLTFFileLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  1802. for (var extensionName in BABYLON.GLTFFileLoader.Extensions) {
  1803. var loaderExtension = BABYLON.GLTFFileLoader.Extensions[extensionName];
  1804. if (func(loaderExtension)) {
  1805. return;
  1806. }
  1807. }
  1808. defaultFunc();
  1809. };
  1810. return GLTFFileLoaderExtension;
  1811. }());
  1812. BABYLON.GLTFFileLoaderExtension = GLTFFileLoaderExtension;
  1813. })(BABYLON || (BABYLON = {}));
  1814. var __extends = (this && this.__extends) || function (d, b) {
  1815. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  1816. function __() { this.constructor = d; }
  1817. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1818. };
  1819. var BABYLON;
  1820. (function (BABYLON) {
  1821. var BinaryExtensionBufferName = "binary_glTF";
  1822. var EContentFormat;
  1823. (function (EContentFormat) {
  1824. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  1825. })(EContentFormat || (EContentFormat = {}));
  1826. ;
  1827. ;
  1828. ;
  1829. ;
  1830. var GLTFBinaryExtension = (function (_super) {
  1831. __extends(GLTFBinaryExtension, _super);
  1832. function GLTFBinaryExtension() {
  1833. _super.call(this, "KHR_binary_glTF");
  1834. }
  1835. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1836. var _this = this;
  1837. if (!(data instanceof ArrayBuffer)) {
  1838. return false;
  1839. }
  1840. setTimeout(function () {
  1841. _this._binary = _this._parseBinary(data);
  1842. if (!_this._binary) {
  1843. onError();
  1844. return true;
  1845. }
  1846. var gltfRuntime = BABYLON.GLTFFileLoaderBase.CreateRuntime(_this._binary.content, scene, rootUrl);
  1847. if (gltfRuntime.extensionsUsed.indexOf(_this.name) === -1) {
  1848. BABYLON.Tools.Warn("glTF binary file does not have " + _this.name + " specified in extensionsUsed");
  1849. gltfRuntime.extensionsUsed.push(_this.name);
  1850. }
  1851. onSuccess(gltfRuntime);
  1852. });
  1853. return true;
  1854. };
  1855. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1856. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  1857. return false;
  1858. }
  1859. if (id !== BinaryExtensionBufferName) {
  1860. return false;
  1861. }
  1862. onSuccess(this._binary.body);
  1863. return true;
  1864. };
  1865. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1866. var texture = gltfRuntime.textures[id];
  1867. var source = gltfRuntime.images[texture.source];
  1868. if (!source.extensions || !(this.name in source.extensions)) {
  1869. return false;
  1870. }
  1871. var sourceExt = source.extensions[this.name];
  1872. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  1873. var buffer = BABYLON.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, BABYLON.EComponentType.UNSIGNED_BYTE);
  1874. onSuccess(buffer);
  1875. return true;
  1876. };
  1877. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1878. var shader = gltfRuntime.shaders[id];
  1879. if (!shader.extensions || !(this.name in shader.extensions)) {
  1880. return false;
  1881. }
  1882. var binaryExtensionShader = shader.extensions[this.name];
  1883. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  1884. var shaderBytes = BABYLON.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, BABYLON.EComponentType.UNSIGNED_BYTE);
  1885. setTimeout(function () {
  1886. var shaderString = BABYLON.GLTFUtils.DecodeBufferToText(shaderBytes);
  1887. onSuccess(shaderString);
  1888. });
  1889. return true;
  1890. };
  1891. // Parses a glTF binary array buffer into its content and body
  1892. GLTFBinaryExtension.prototype._parseBinary = function (data) {
  1893. var binaryReader = new BinaryReader(data);
  1894. var magic = BABYLON.GLTFUtils.DecodeBufferToText(binaryReader.getUint8Array(4));
  1895. if (magic != "glTF") {
  1896. BABYLON.Tools.Error("Unexpected magic: " + magic);
  1897. return null;
  1898. }
  1899. var version = binaryReader.getUint32();
  1900. if (version != 1) {
  1901. BABYLON.Tools.Error("Unsupported version: " + version);
  1902. return null;
  1903. }
  1904. var length = binaryReader.getUint32();
  1905. if (length != data.byteLength) {
  1906. BABYLON.Tools.Error("Length in header does not match actual data length: " + length + " != " + data.byteLength);
  1907. return null;
  1908. }
  1909. var contentLength = binaryReader.getUint32();
  1910. var contentFormat = binaryReader.getUint32();
  1911. var content;
  1912. switch (contentFormat) {
  1913. case EContentFormat.JSON:
  1914. var jsonText = BABYLON.GLTFUtils.DecodeBufferToText(binaryReader.getUint8Array(contentLength));
  1915. content = JSON.parse(jsonText);
  1916. break;
  1917. default:
  1918. BABYLON.Tools.Error("Unexpected content format: " + contentFormat);
  1919. return null;
  1920. }
  1921. var body = binaryReader.getUint8Array();
  1922. return {
  1923. content: content,
  1924. body: body
  1925. };
  1926. };
  1927. ;
  1928. return GLTFBinaryExtension;
  1929. }(BABYLON.GLTFFileLoaderExtension));
  1930. BABYLON.GLTFBinaryExtension = GLTFBinaryExtension;
  1931. var BinaryReader = (function () {
  1932. function BinaryReader(arrayBuffer) {
  1933. this._arrayBuffer = arrayBuffer;
  1934. this._dataView = new DataView(arrayBuffer);
  1935. this._byteOffset = 0;
  1936. }
  1937. BinaryReader.prototype.getUint32 = function () {
  1938. var value = this._dataView.getUint32(this._byteOffset, true);
  1939. this._byteOffset += 4;
  1940. return value;
  1941. };
  1942. BinaryReader.prototype.getUint8Array = function (length) {
  1943. if (!length) {
  1944. length = this._arrayBuffer.byteLength - this._byteOffset;
  1945. }
  1946. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  1947. this._byteOffset += length;
  1948. return value;
  1949. };
  1950. return BinaryReader;
  1951. }());
  1952. BABYLON.GLTFFileLoader.RegisterExtension(new GLTFBinaryExtension());
  1953. })(BABYLON || (BABYLON = {}));