babylon.glTFFileLoader.js 89 KB

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