babylon.glTFFileLoader.js 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968
  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=../../src/glTF/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. newMesh.material = multiMat;
  598. var vertexData = new BABYLON.VertexData();
  599. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  600. var verticesStarts = [];
  601. var verticesCounts = [];
  602. var indexStarts = [];
  603. var indexCounts = [];
  604. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  605. var meshID = meshes[meshIndex];
  606. var mesh = gltfRuntime.meshes[meshID];
  607. if (!mesh) {
  608. continue;
  609. }
  610. // Positions, normals and UVs
  611. for (var i = 0; i < mesh.primitives.length; i++) {
  612. // Temporary vertex data
  613. var tempVertexData = new BABYLON.VertexData();
  614. var primitive = mesh.primitives[i];
  615. if (primitive.mode !== 4) {
  616. }
  617. var attributes = primitive.attributes;
  618. var accessor = null;
  619. var buffer = null;
  620. // Set positions, normal and uvs
  621. for (var semantic in attributes) {
  622. // Link accessor and buffer view
  623. accessor = gltfRuntime.accessors[attributes[semantic]];
  624. buffer = BABYLON.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  625. if (semantic === "NORMAL") {
  626. tempVertexData.normals = new Float32Array(buffer.length);
  627. tempVertexData.normals.set(buffer);
  628. }
  629. else if (semantic === "POSITION") {
  630. if (GLTFFileLoader.HomogeneousCoordinates) {
  631. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  632. for (var j = 0; j < buffer.length; j += 4) {
  633. tempVertexData.positions[j] = buffer[j];
  634. tempVertexData.positions[j + 1] = buffer[j + 1];
  635. tempVertexData.positions[j + 2] = buffer[j + 2];
  636. }
  637. }
  638. else {
  639. tempVertexData.positions = new Float32Array(buffer.length);
  640. tempVertexData.positions.set(buffer);
  641. }
  642. verticesCounts.push(tempVertexData.positions.length);
  643. }
  644. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  645. var channel = Number(semantic.split("_")[1]);
  646. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  647. var uvs = new Float32Array(buffer.length);
  648. uvs.set(buffer);
  649. normalizeUVs(uvs);
  650. tempVertexData.set(uvs, uvKind);
  651. }
  652. else if (semantic === "JOINT") {
  653. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  654. tempVertexData.matricesIndices.set(buffer);
  655. }
  656. else if (semantic === "WEIGHT") {
  657. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  658. tempVertexData.matricesWeights.set(buffer);
  659. }
  660. else if (semantic === "COLOR") {
  661. tempVertexData.colors = new Float32Array(buffer.length);
  662. tempVertexData.colors.set(buffer);
  663. }
  664. }
  665. // Indices
  666. accessor = gltfRuntime.accessors[primitive.indices];
  667. buffer = BABYLON.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  668. tempVertexData.indices = new Int32Array(buffer.length);
  669. tempVertexData.indices.set(buffer);
  670. indexCounts.push(tempVertexData.indices.length);
  671. vertexData.merge(tempVertexData);
  672. tempVertexData = undefined;
  673. // Sub material
  674. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  675. multiMat.subMaterials.push(material === null ? gltfRuntime.scene.defaultMaterial : material);
  676. // Update vertices start and index start
  677. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  678. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  679. }
  680. }
  681. // Apply geometry
  682. geometry.setAllVerticesData(vertexData, false);
  683. newMesh.computeWorldMatrix(true);
  684. // Apply submeshes
  685. newMesh.subMeshes = [];
  686. var index = 0;
  687. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  688. var meshID = meshes[meshIndex];
  689. var mesh = gltfRuntime.meshes[meshID];
  690. if (!mesh) {
  691. continue;
  692. }
  693. for (var i = 0; i < mesh.primitives.length; i++) {
  694. if (mesh.primitives[i].mode !== 4) {
  695. }
  696. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  697. index++;
  698. }
  699. }
  700. // Finish
  701. return newMesh;
  702. };
  703. /**
  704. * Configure node transformation from position, rotation and scaling
  705. */
  706. var configureNode = function (newNode, position, rotation, scaling) {
  707. if (newNode.position) {
  708. newNode.position = position;
  709. }
  710. if (newNode.rotationQuaternion || newNode.rotation) {
  711. newNode.rotationQuaternion = rotation;
  712. }
  713. if (newNode.scaling) {
  714. newNode.scaling = scaling;
  715. }
  716. };
  717. /**
  718. * Configures node from transformation matrix
  719. */
  720. var configureNodeFromMatrix = function (newNode, node) {
  721. if (node.matrix) {
  722. var position = new BABYLON.Vector3(0, 0, 0);
  723. var rotation = new BABYLON.Quaternion();
  724. var scaling = new BABYLON.Vector3(0, 0, 0);
  725. var mat = BABYLON.Matrix.FromArray(node.matrix);
  726. mat.decompose(scaling, rotation, position);
  727. // Y is Up
  728. if (GLTFFileLoader.MakeYUP) {
  729. rotation = rotation.multiply(new BABYLON.Quaternion(-0.707107, 0, 0, 0.707107));
  730. }
  731. configureNode(newNode, position, rotation, scaling);
  732. if (newNode instanceof BABYLON.TargetCamera) {
  733. newNode.setTarget(BABYLON.Vector3.Zero());
  734. }
  735. }
  736. else {
  737. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  738. }
  739. };
  740. /**
  741. * Imports a node
  742. */
  743. var importNode = function (gltfRuntime, node, id) {
  744. var lastNode = null;
  745. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  746. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  747. return null;
  748. }
  749. }
  750. // Meshes
  751. if (node.skin) {
  752. if (node.meshes) {
  753. var skin = gltfRuntime.skins[node.skin];
  754. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  755. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  756. if (newMesh.skeleton === null) {
  757. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  758. if (!skin.babylonSkeleton) {
  759. skin.babylonSkeleton = newMesh.skeleton;
  760. }
  761. }
  762. if (newMesh.skeleton !== null) {
  763. newMesh.useBones = true;
  764. }
  765. lastNode = newMesh;
  766. }
  767. }
  768. else if (node.meshes) {
  769. /**
  770. * Improve meshes property
  771. */
  772. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  773. lastNode = newMesh;
  774. }
  775. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  776. var light = gltfRuntime.lights[node.light];
  777. if (light) {
  778. if (light.type === "ambient") {
  779. var ambienLight = light[light.type];
  780. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  781. hemiLight.name = node.name;
  782. if (ambienLight.color) {
  783. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  784. }
  785. lastNode = hemiLight;
  786. }
  787. else if (light.type === "directional") {
  788. var directionalLight = light[light.type];
  789. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  790. dirLight.name = node.name;
  791. if (directionalLight.color) {
  792. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  793. }
  794. lastNode = dirLight;
  795. }
  796. else if (light.type === "point") {
  797. var pointLight = light[light.type];
  798. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  799. ptLight.name = node.name;
  800. if (pointLight.color) {
  801. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  802. }
  803. lastNode = ptLight;
  804. }
  805. else if (light.type === "spot") {
  806. var spotLight = light[light.type];
  807. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  808. spLight.name = node.name;
  809. if (spotLight.color) {
  810. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  811. }
  812. if (spotLight.fallOfAngle) {
  813. spLight.angle = spotLight.fallOfAngle;
  814. }
  815. if (spotLight.fallOffExponent) {
  816. spLight.exponent = spotLight.fallOffExponent;
  817. }
  818. lastNode = spLight;
  819. }
  820. }
  821. }
  822. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  823. var camera = gltfRuntime.cameras[node.camera];
  824. if (camera) {
  825. if (camera.type === "orthographic") {
  826. var orthographicCamera = camera[camera.type];
  827. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  828. orthoCamera.name = node.name;
  829. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  830. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  831. lastNode = orthoCamera;
  832. }
  833. else if (camera.type === "perspective") {
  834. var perspectiveCamera = camera[camera.type];
  835. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  836. persCamera.name = node.name;
  837. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  838. if (!perspectiveCamera.aspectRatio) {
  839. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  840. }
  841. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  842. persCamera.maxZ = perspectiveCamera.zfar;
  843. persCamera.minZ = perspectiveCamera.znear;
  844. }
  845. lastNode = persCamera;
  846. }
  847. }
  848. }
  849. // Empty node
  850. if (!node.jointName) {
  851. if (node.babylonNode) {
  852. return node.babylonNode;
  853. }
  854. else if (lastNode === null) {
  855. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  856. node.babylonNode = dummy;
  857. lastNode = dummy;
  858. }
  859. }
  860. if (lastNode !== null) {
  861. if (node.matrix) {
  862. configureNodeFromMatrix(lastNode, node);
  863. }
  864. else {
  865. configureNode(lastNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.RotationAxis(BABYLON.Vector3.FromArray(node.rotation).normalize(), node.rotation[3]), BABYLON.Vector3.FromArray(node.scale));
  866. }
  867. lastNode.updateCache(true);
  868. node.babylonNode = lastNode;
  869. }
  870. return lastNode;
  871. };
  872. /**
  873. * Traverses nodes and creates them
  874. */
  875. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  876. var node = gltfRuntime.nodes[id];
  877. var newNode = null;
  878. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  879. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  880. meshIncluded = true;
  881. }
  882. else {
  883. meshIncluded = false;
  884. }
  885. }
  886. else {
  887. meshIncluded = true;
  888. }
  889. if (!node.jointName && meshIncluded) {
  890. newNode = importNode(gltfRuntime, node, id);
  891. if (newNode !== null) {
  892. newNode.id = id;
  893. newNode.parent = parent;
  894. }
  895. }
  896. for (var i = 0; i < node.children.length; i++) {
  897. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  898. }
  899. };
  900. /**
  901. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  902. */
  903. var postLoad = function (gltfRuntime) {
  904. // Nodes
  905. var currentScene = gltfRuntime.currentScene;
  906. for (var i = 0; i < currentScene.nodes.length; i++) {
  907. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  908. }
  909. // Set animations
  910. loadAnimations(gltfRuntime);
  911. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  912. var skeleton = gltfRuntime.scene.skeletons[i];
  913. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  914. }
  915. };
  916. /**
  917. * onBind shaderrs callback to set uniforms and matrices
  918. */
  919. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  920. for (var unif in unTreatedUniforms) {
  921. var uniform = unTreatedUniforms[unif];
  922. var type = uniform.type;
  923. if (type === BABYLON.EParameterType.FLOAT_MAT2 || type === BABYLON.EParameterType.FLOAT_MAT3 || type === BABYLON.EParameterType.FLOAT_MAT4) {
  924. if (uniform.semantic && !uniform.source && !uniform.node) {
  925. BABYLON.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  926. }
  927. else if (uniform.semantic && (uniform.source || uniform.node)) {
  928. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  929. if (source === null) {
  930. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  931. }
  932. if (source === null) {
  933. continue;
  934. }
  935. BABYLON.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  936. }
  937. }
  938. else {
  939. var value = material.values[technique.uniforms[unif]];
  940. if (!value) {
  941. continue;
  942. }
  943. if (type === BABYLON.EParameterType.SAMPLER_2D) {
  944. var texture = gltfRuntime.textures[value].babylonTexture;
  945. if (texture === null) {
  946. continue;
  947. }
  948. shaderMaterial.getEffect().setTexture(unif, texture);
  949. }
  950. else {
  951. BABYLON.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  952. }
  953. }
  954. }
  955. onSuccess(shaderMaterial);
  956. };
  957. /**
  958. * Prepare uniforms to send the only one time
  959. * Loads the appropriate textures
  960. */
  961. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  962. var materialValues = material.values;
  963. var techniqueUniforms = technique.uniforms;
  964. /**
  965. * Prepare values here (not matrices)
  966. */
  967. for (var unif in unTreatedUniforms) {
  968. var uniform = unTreatedUniforms[unif];
  969. var type = uniform.type;
  970. var value = materialValues[techniqueUniforms[unif]] || uniform.value;
  971. if (!value) {
  972. continue;
  973. }
  974. var onLoadTexture = function (texture) {
  975. if (uniform.value) {
  976. // Static uniform
  977. shaderMaterial.setTexture(unif, texture);
  978. delete unTreatedUniforms[unif];
  979. }
  980. };
  981. // Texture (sampler2D)
  982. if (type === BABYLON.EParameterType.SAMPLER_2D) {
  983. BABYLON.GLTFFileLoaderExtension.LoadTextureAsync(gltfRuntime, value, onLoadTexture, function () { return onLoadTexture(null); });
  984. }
  985. else {
  986. if (uniform.value && BABYLON.GLTFUtils.SetUniform(shaderMaterial, unif, value, type)) {
  987. // Static uniform
  988. delete unTreatedUniforms[unif];
  989. }
  990. }
  991. }
  992. };
  993. /**
  994. * Shader compilation failed
  995. */
  996. var onShaderCompileError = function (program, shaderMaterial, onError) {
  997. return function (effect, error) {
  998. BABYLON.Tools.Error("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  999. shaderMaterial.dispose(true);
  1000. onError();
  1001. };
  1002. };
  1003. /**
  1004. * Shader compilation success
  1005. */
  1006. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1007. return function (_) {
  1008. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1009. shaderMaterial.onBind = function (mesh) {
  1010. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1011. };
  1012. };
  1013. };
  1014. /**
  1015. * Returns the appropriate uniform if already handled by babylon
  1016. */
  1017. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1018. for (var unif in technique.uniforms) {
  1019. var uniform = technique.uniforms[unif];
  1020. var uniformParameter = technique.parameters[uniform];
  1021. if (tokenizer.currentIdentifier === unif) {
  1022. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1023. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1024. if (transformIndex !== -1) {
  1025. delete unTreatedUniforms[unif];
  1026. return babylonTransforms[transformIndex];
  1027. }
  1028. }
  1029. }
  1030. }
  1031. return tokenizer.currentIdentifier;
  1032. };
  1033. /**
  1034. * All shaders loaded. Create materials one by one
  1035. */
  1036. var importMaterials = function (gltfRuntime) {
  1037. // Create materials
  1038. for (var mat in gltfRuntime.materials) {
  1039. BABYLON.GLTFFileLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1040. }
  1041. };
  1042. /**
  1043. * Implementation of the base glTF spec
  1044. */
  1045. var GLTFFileLoaderBase = (function () {
  1046. function GLTFFileLoaderBase() {
  1047. }
  1048. GLTFFileLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1049. var gltfRuntime = {
  1050. accessors: {},
  1051. buffers: {},
  1052. bufferViews: {},
  1053. meshes: {},
  1054. lights: {},
  1055. cameras: {},
  1056. nodes: {},
  1057. images: {},
  1058. textures: {},
  1059. shaders: {},
  1060. programs: {},
  1061. samplers: {},
  1062. techniques: {},
  1063. materials: {},
  1064. animations: {},
  1065. skins: {},
  1066. currentScene: {},
  1067. extensionsUsed: [],
  1068. buffersCount: 0,
  1069. shaderscount: 0,
  1070. scene: scene,
  1071. rootUrl: rootUrl,
  1072. loadedBufferCount: 0,
  1073. loadedBufferViews: {},
  1074. loadedShaderCount: 0,
  1075. importOnlyMeshes: false,
  1076. dummyNodes: []
  1077. };
  1078. // Parse
  1079. if (parsedData.extensionsUsed) {
  1080. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1081. }
  1082. if (parsedData.buffers) {
  1083. parseBuffers(parsedData.buffers, gltfRuntime);
  1084. }
  1085. if (parsedData.bufferViews) {
  1086. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1087. }
  1088. if (parsedData.accessors) {
  1089. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1090. }
  1091. if (parsedData.meshes) {
  1092. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1093. }
  1094. if (parsedData.lights) {
  1095. parseObject(parsedData.lights, "lights", gltfRuntime);
  1096. }
  1097. if (parsedData.cameras) {
  1098. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1099. }
  1100. if (parsedData.nodes) {
  1101. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1102. }
  1103. if (parsedData.images) {
  1104. parseObject(parsedData.images, "images", gltfRuntime);
  1105. }
  1106. if (parsedData.textures) {
  1107. parseObject(parsedData.textures, "textures", gltfRuntime);
  1108. }
  1109. if (parsedData.shaders) {
  1110. parseShaders(parsedData.shaders, gltfRuntime);
  1111. }
  1112. if (parsedData.programs) {
  1113. parseObject(parsedData.programs, "programs", gltfRuntime);
  1114. }
  1115. if (parsedData.samplers) {
  1116. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1117. }
  1118. if (parsedData.techniques) {
  1119. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1120. }
  1121. if (parsedData.materials) {
  1122. parseObject(parsedData.materials, "materials", gltfRuntime);
  1123. }
  1124. if (parsedData.animations) {
  1125. parseObject(parsedData.animations, "animations", gltfRuntime);
  1126. }
  1127. if (parsedData.skins) {
  1128. parseObject(parsedData.skins, "skins", gltfRuntime);
  1129. }
  1130. if (parsedData.scene && parsedData.scenes) {
  1131. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1132. }
  1133. return gltfRuntime;
  1134. };
  1135. GLTFFileLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1136. var buffer = gltfRuntime.buffers[id];
  1137. if (BABYLON.GLTFUtils.IsBase64(buffer.uri)) {
  1138. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.GLTFUtils.DecodeBase64(buffer.uri))); });
  1139. }
  1140. else {
  1141. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, onError);
  1142. }
  1143. };
  1144. GLTFFileLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1145. var texture = gltfRuntime.textures[id];
  1146. if (!texture || !texture.source) {
  1147. onError();
  1148. return;
  1149. }
  1150. if (texture.babylonTexture) {
  1151. onSuccess(null);
  1152. return;
  1153. }
  1154. var source = gltfRuntime.images[texture.source];
  1155. if (BABYLON.GLTFUtils.IsBase64(source.uri)) {
  1156. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.GLTFUtils.DecodeBase64(source.uri))); });
  1157. }
  1158. else {
  1159. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, onError);
  1160. }
  1161. };
  1162. GLTFFileLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1163. var texture = gltfRuntime.textures[id];
  1164. if (texture.babylonTexture) {
  1165. onSuccess(texture.babylonTexture);
  1166. return;
  1167. }
  1168. var sampler = gltfRuntime.samplers[texture.sampler];
  1169. var createMipMaps = (sampler.minFilter === BABYLON.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1170. (sampler.minFilter === BABYLON.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1171. (sampler.minFilter === BABYLON.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1172. (sampler.minFilter === BABYLON.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1173. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1174. var blob = new Blob([buffer]);
  1175. var blobURL = URL.createObjectURL(blob);
  1176. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1177. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1178. newTexture.wrapU = BABYLON.GLTFUtils.GetWrapMode(sampler.wrapS);
  1179. newTexture.wrapV = BABYLON.GLTFUtils.GetWrapMode(sampler.wrapT);
  1180. newTexture.name = id;
  1181. texture.babylonTexture = newTexture;
  1182. onSuccess(newTexture);
  1183. };
  1184. GLTFFileLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1185. var shader = gltfRuntime.shaders[id];
  1186. if (BABYLON.GLTFUtils.IsBase64(shader.uri)) {
  1187. var shaderString = atob(shader.uri.split(",")[1]);
  1188. onSuccess(shaderString);
  1189. }
  1190. else {
  1191. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, onError);
  1192. }
  1193. };
  1194. GLTFFileLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1195. var material = gltfRuntime.materials[id];
  1196. var technique = gltfRuntime.techniques[material.technique];
  1197. if (!technique) {
  1198. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1199. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  1200. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1201. onSuccess(defaultMaterial);
  1202. return;
  1203. }
  1204. var program = gltfRuntime.programs[technique.program];
  1205. var states = technique.states;
  1206. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1207. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1208. var newVertexShader = "";
  1209. var newPixelShader = "";
  1210. var vertexTokenizer = new Tokenizer(vertexShader);
  1211. var pixelTokenizer = new Tokenizer(pixelShader);
  1212. var unTreatedUniforms = {};
  1213. var uniforms = [];
  1214. var attributes = [];
  1215. var samplers = [];
  1216. // Fill uniform, sampler2D and attributes
  1217. for (var unif in technique.uniforms) {
  1218. var uniform = technique.uniforms[unif];
  1219. var uniformParameter = technique.parameters[uniform];
  1220. unTreatedUniforms[unif] = uniformParameter;
  1221. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1222. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1223. if (transformIndex !== -1) {
  1224. uniforms.push(babylonTransforms[transformIndex]);
  1225. delete unTreatedUniforms[unif];
  1226. }
  1227. else {
  1228. uniforms.push(unif);
  1229. }
  1230. }
  1231. else if (uniformParameter.type === BABYLON.EParameterType.SAMPLER_2D) {
  1232. samplers.push(unif);
  1233. }
  1234. else {
  1235. uniforms.push(unif);
  1236. }
  1237. }
  1238. for (var attr in technique.attributes) {
  1239. var attribute = technique.attributes[attr];
  1240. var attributeParameter = technique.parameters[attribute];
  1241. if (attributeParameter.semantic) {
  1242. attributes.push(getAttribute(attributeParameter));
  1243. }
  1244. }
  1245. // Configure vertex shader
  1246. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1247. var tokenType = vertexTokenizer.currentToken;
  1248. if (tokenType !== ETokenType.IDENTIFIER) {
  1249. newVertexShader += vertexTokenizer.currentString;
  1250. continue;
  1251. }
  1252. var foundAttribute = false;
  1253. for (var attr in technique.attributes) {
  1254. var attribute = technique.attributes[attr];
  1255. var attributeParameter = technique.parameters[attribute];
  1256. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1257. newVertexShader += getAttribute(attributeParameter);
  1258. foundAttribute = true;
  1259. break;
  1260. }
  1261. }
  1262. if (foundAttribute) {
  1263. continue;
  1264. }
  1265. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1266. }
  1267. // Configure pixel shader
  1268. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1269. var tokenType = pixelTokenizer.currentToken;
  1270. if (tokenType !== ETokenType.IDENTIFIER) {
  1271. newPixelShader += pixelTokenizer.currentString;
  1272. continue;
  1273. }
  1274. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1275. }
  1276. // Create shader material
  1277. var shaderPath = {
  1278. vertex: program.vertexShader + id,
  1279. fragment: program.fragmentShader + id
  1280. };
  1281. var options = {
  1282. attributes: attributes,
  1283. uniforms: uniforms,
  1284. samplers: samplers,
  1285. needAlphaBlending: states.functions && states.functions.blendEquationSeparate
  1286. };
  1287. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1288. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1289. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1290. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1291. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1292. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1293. if (states.functions) {
  1294. var functions = states.functions;
  1295. if (functions.cullFace && functions.cullFace[0] !== BABYLON.ECullingType.BACK) {
  1296. shaderMaterial.backFaceCulling = false;
  1297. }
  1298. var blendFunc = functions.blendFuncSeparate;
  1299. if (blendFunc) {
  1300. 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) {
  1301. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1302. }
  1303. else if (blendFunc[0] === BABYLON.EBlendingFunction.ONE && blendFunc[1] === BABYLON.EBlendingFunction.ONE && blendFunc[2] === BABYLON.EBlendingFunction.ZERO && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1304. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  1305. }
  1306. else if (blendFunc[0] === BABYLON.EBlendingFunction.SRC_ALPHA && blendFunc[1] === BABYLON.EBlendingFunction.ONE && blendFunc[2] === BABYLON.EBlendingFunction.ZERO && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1307. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  1308. }
  1309. 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) {
  1310. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  1311. }
  1312. else if (blendFunc[0] === BABYLON.EBlendingFunction.DST_COLOR && blendFunc[1] === BABYLON.EBlendingFunction.ZERO && blendFunc[2] === BABYLON.EBlendingFunction.ONE && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1313. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  1314. }
  1315. 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) {
  1316. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  1317. }
  1318. }
  1319. }
  1320. };
  1321. return GLTFFileLoaderBase;
  1322. }());
  1323. BABYLON.GLTFFileLoaderBase = GLTFFileLoaderBase;
  1324. /**
  1325. * glTF File Loader Plugin
  1326. */
  1327. var GLTFFileLoader = (function () {
  1328. function GLTFFileLoader() {
  1329. /**
  1330. * Public members
  1331. */
  1332. this.extensions = {
  1333. ".gltf": { isBinary: false },
  1334. ".glb": { isBinary: true }
  1335. };
  1336. }
  1337. GLTFFileLoader.RegisterExtension = function (extension) {
  1338. if (GLTFFileLoader.Extensions[extension.name]) {
  1339. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1340. return;
  1341. }
  1342. GLTFFileLoader.Extensions[extension.name] = extension;
  1343. };
  1344. /**
  1345. * Import meshes
  1346. */
  1347. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onError) {
  1348. var _this = this;
  1349. scene.useRightHandedSystem = true;
  1350. var gltfRuntime = BABYLON.GLTFFileLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1351. gltfRuntime.importOnlyMeshes = true;
  1352. if (meshesNames === "") {
  1353. gltfRuntime.importMeshesNames = [];
  1354. }
  1355. else if (typeof meshesNames === "string") {
  1356. gltfRuntime.importMeshesNames = [meshesNames];
  1357. }
  1358. else if (meshesNames && !(meshesNames instanceof Array)) {
  1359. gltfRuntime.importMeshesNames = [meshesNames];
  1360. }
  1361. else {
  1362. gltfRuntime.importMeshesNames = [];
  1363. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1364. }
  1365. // Create nodes
  1366. _this._createNodes(gltfRuntime);
  1367. var meshes = [];
  1368. var skeletons = [];
  1369. // Fill arrays of meshes and skeletons
  1370. for (var nde in gltfRuntime.nodes) {
  1371. var node = gltfRuntime.nodes[nde];
  1372. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1373. meshes.push(node.babylonNode);
  1374. }
  1375. }
  1376. for (var skl in gltfRuntime.skins) {
  1377. var skin = gltfRuntime.skins[skl];
  1378. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1379. skeletons.push(skin.babylonSkeleton);
  1380. }
  1381. }
  1382. // Load buffers, shaders, materials, etc.
  1383. _this._loadBuffersAsync(gltfRuntime, function () {
  1384. _this._loadShadersAsync(gltfRuntime, function () {
  1385. importMaterials(gltfRuntime);
  1386. postLoad(gltfRuntime);
  1387. });
  1388. });
  1389. if (onSuccess) {
  1390. onSuccess(meshes, null, skeletons);
  1391. }
  1392. }, onError);
  1393. return true;
  1394. };
  1395. /**
  1396. * Load scene
  1397. */
  1398. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1399. var _this = this;
  1400. scene.useRightHandedSystem = true;
  1401. BABYLON.GLTFFileLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1402. // Create nodes
  1403. _this._createNodes(gltfRuntime);
  1404. // Load buffers, shaders, materials, etc.
  1405. _this._loadBuffersAsync(gltfRuntime, function () {
  1406. _this._loadShadersAsync(gltfRuntime, function () {
  1407. importMaterials(gltfRuntime);
  1408. postLoad(gltfRuntime);
  1409. });
  1410. });
  1411. onSuccess();
  1412. }, onError);
  1413. return true;
  1414. };
  1415. GLTFFileLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1416. var hasShaders = false;
  1417. var processShader = function (sha, shader) {
  1418. BABYLON.GLTFFileLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1419. gltfRuntime.loadedShaderCount++;
  1420. if (shaderString) {
  1421. BABYLON.Effect.ShadersStore[sha + (shader.type === BABYLON.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1422. }
  1423. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1424. onload();
  1425. }
  1426. }, function () {
  1427. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1428. });
  1429. };
  1430. for (var sha in gltfRuntime.shaders) {
  1431. hasShaders = true;
  1432. var shader = gltfRuntime.shaders[sha];
  1433. if (shader) {
  1434. processShader.bind(this, sha, shader)();
  1435. }
  1436. else {
  1437. BABYLON.Tools.Error("No shader named: " + sha);
  1438. }
  1439. }
  1440. if (!hasShaders) {
  1441. onload();
  1442. }
  1443. };
  1444. ;
  1445. GLTFFileLoader.prototype._loadBuffersAsync = function (gltfRuntime, onload) {
  1446. var hasBuffers = false;
  1447. var processBuffer = function (buf, buffer) {
  1448. BABYLON.GLTFFileLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  1449. gltfRuntime.loadedBufferCount++;
  1450. if (bufferView) {
  1451. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1452. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1453. }
  1454. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1455. }
  1456. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1457. onload();
  1458. }
  1459. }, function () {
  1460. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1461. });
  1462. };
  1463. for (var buf in gltfRuntime.buffers) {
  1464. hasBuffers = true;
  1465. var buffer = gltfRuntime.buffers[buf];
  1466. if (buffer) {
  1467. processBuffer.bind(this, buf, buffer)();
  1468. }
  1469. else {
  1470. BABYLON.Tools.Error("No buffer named: " + buf);
  1471. }
  1472. }
  1473. if (!hasBuffers) {
  1474. onload();
  1475. }
  1476. };
  1477. // Creates nodes before loading buffers and shaders
  1478. GLTFFileLoader.prototype._createNodes = function (gltfRuntime) {
  1479. var currentScene = gltfRuntime.currentScene;
  1480. for (var i = 0; i < currentScene.nodes.length; i++) {
  1481. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1482. }
  1483. };
  1484. /**
  1485. * Private members
  1486. */
  1487. // None
  1488. /**
  1489. * Static members
  1490. */
  1491. GLTFFileLoader.MakeYUP = false;
  1492. GLTFFileLoader.HomogeneousCoordinates = false;
  1493. GLTFFileLoader.Extensions = {};
  1494. return GLTFFileLoader;
  1495. }());
  1496. BABYLON.GLTFFileLoader = GLTFFileLoader;
  1497. ;
  1498. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  1499. })(BABYLON || (BABYLON = {}));
  1500. //# sourceMappingURL=../../src/glTF/babylon.glTFFileLoader.js.map
  1501. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  1502. var BABYLON;
  1503. (function (BABYLON) {
  1504. /**
  1505. * Utils functions for GLTF
  1506. */
  1507. var GLTFUtils = (function () {
  1508. function GLTFUtils() {
  1509. }
  1510. /**
  1511. * Sets the given "parameter" matrix
  1512. * @param scene: the {BABYLON.Scene} object
  1513. * @param source: the source node where to pick the matrix
  1514. * @param parameter: the GLTF technique parameter
  1515. * @param uniformName: the name of the shader's uniform
  1516. * @param shaderMaterial: the shader material
  1517. */
  1518. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  1519. var mat = null;
  1520. if (parameter.semantic === "MODEL") {
  1521. mat = source.getWorldMatrix();
  1522. }
  1523. else if (parameter.semantic === "PROJECTION") {
  1524. mat = scene.getProjectionMatrix();
  1525. }
  1526. else if (parameter.semantic === "VIEW") {
  1527. mat = scene.getViewMatrix();
  1528. }
  1529. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  1530. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  1531. }
  1532. else if (parameter.semantic === "MODELVIEW") {
  1533. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  1534. }
  1535. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  1536. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  1537. }
  1538. else if (parameter.semantic === "MODELINVERSE") {
  1539. mat = source.getWorldMatrix().invert();
  1540. }
  1541. else if (parameter.semantic === "VIEWINVERSE") {
  1542. mat = scene.getViewMatrix().invert();
  1543. }
  1544. else if (parameter.semantic === "PROJECTIONINVERSE") {
  1545. mat = scene.getProjectionMatrix().invert();
  1546. }
  1547. else if (parameter.semantic === "MODELVIEWINVERSE") {
  1548. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  1549. }
  1550. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  1551. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  1552. }
  1553. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  1554. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  1555. }
  1556. else {
  1557. debugger;
  1558. }
  1559. switch (parameter.type) {
  1560. case BABYLON.EParameterType.FLOAT_MAT2:
  1561. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  1562. break;
  1563. case BABYLON.EParameterType.FLOAT_MAT3:
  1564. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  1565. break;
  1566. case BABYLON.EParameterType.FLOAT_MAT4:
  1567. shaderMaterial.setMatrix(uniformName, mat);
  1568. break;
  1569. default: break;
  1570. }
  1571. };
  1572. /**
  1573. * Sets the given "parameter" matrix
  1574. * @param shaderMaterial: the shader material
  1575. * @param uniform: the name of the shader's uniform
  1576. * @param value: the value of the uniform
  1577. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  1578. */
  1579. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  1580. switch (type) {
  1581. case BABYLON.EParameterType.FLOAT:
  1582. shaderMaterial.setFloat(uniform, value);
  1583. return true;
  1584. case BABYLON.EParameterType.FLOAT_VEC2:
  1585. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  1586. return true;
  1587. case BABYLON.EParameterType.FLOAT_VEC3:
  1588. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  1589. return true;
  1590. case BABYLON.EParameterType.FLOAT_VEC4:
  1591. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  1592. return true;
  1593. default: return false;
  1594. }
  1595. };
  1596. /**
  1597. * If the uri is a base64 string
  1598. * @param uri: the uri to test
  1599. */
  1600. GLTFUtils.IsBase64 = function (uri) {
  1601. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1602. };
  1603. /**
  1604. * Decode the base64 uri
  1605. * @param uri: the uri to decode
  1606. */
  1607. GLTFUtils.DecodeBase64 = function (uri) {
  1608. var decodedString = atob(uri.split(",")[1]);
  1609. var bufferLength = decodedString.length;
  1610. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1611. for (var i = 0; i < bufferLength; i++) {
  1612. bufferView[i] = decodedString.charCodeAt(i);
  1613. }
  1614. return bufferView.buffer;
  1615. };
  1616. /**
  1617. * Returns the wrap mode of the texture
  1618. * @param mode: the mode value
  1619. */
  1620. GLTFUtils.GetWrapMode = function (mode) {
  1621. switch (mode) {
  1622. case BABYLON.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1623. case BABYLON.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1624. case BABYLON.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1625. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1626. }
  1627. };
  1628. /**
  1629. * Returns the byte stride giving an accessor
  1630. * @param accessor: the GLTF accessor objet
  1631. */
  1632. GLTFUtils.GetByteStrideFromType = function (accessor) {
  1633. // Needs this function since "byteStride" isn't requiered in glTF format
  1634. var type = accessor.type;
  1635. switch (type) {
  1636. case "VEC2": return 2;
  1637. case "VEC3": return 3;
  1638. case "VEC4": return 4;
  1639. case "MAT2": return 4;
  1640. case "MAT3": return 9;
  1641. case "MAT4": return 16;
  1642. default: return 1;
  1643. }
  1644. };
  1645. /**
  1646. * Returns the texture filter mode giving a mode value
  1647. * @param mode: the filter mode value
  1648. */
  1649. GLTFUtils.GetTextureFilterMode = function (mode) {
  1650. switch (mode) {
  1651. case BABYLON.ETextureFilterType.LINEAR:
  1652. case BABYLON.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  1653. case BABYLON.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1654. case BABYLON.ETextureFilterType.NEAREST:
  1655. case BABYLON.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1656. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1657. }
  1658. };
  1659. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  1660. var byteOffset = bufferView.byteOffset + byteOffset;
  1661. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  1662. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  1663. throw new Error("Buffer access is out of range");
  1664. }
  1665. var buffer = loadedBufferView.buffer;
  1666. byteOffset += loadedBufferView.byteOffset;
  1667. switch (componentType) {
  1668. case BABYLON.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  1669. case BABYLON.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  1670. case BABYLON.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  1671. case BABYLON.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  1672. default: return new Float32Array(buffer, byteOffset, byteLength);
  1673. }
  1674. };
  1675. /**
  1676. * Returns a buffer from its accessor
  1677. * @param gltfRuntime: the GLTF runtime
  1678. * @param accessor: the GLTF accessor
  1679. */
  1680. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  1681. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  1682. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  1683. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  1684. };
  1685. /**
  1686. * Decodes a buffer view into a string
  1687. * @param view: the buffer view
  1688. */
  1689. GLTFUtils.DecodeBufferToText = function (view) {
  1690. var result = "";
  1691. var length = view.byteLength;
  1692. for (var i = 0; i < length; ++i) {
  1693. result += String.fromCharCode(view[i]);
  1694. }
  1695. return result;
  1696. };
  1697. return GLTFUtils;
  1698. }());
  1699. BABYLON.GLTFUtils = GLTFUtils;
  1700. })(BABYLON || (BABYLON = {}));
  1701. //# sourceMappingURL=../../src/glTF/babylon.glTFFileLoaderUtils.js.map
  1702. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  1703. var BABYLON;
  1704. (function (BABYLON) {
  1705. var GLTFFileLoaderExtension = (function () {
  1706. function GLTFFileLoaderExtension(name) {
  1707. this._name = name;
  1708. }
  1709. Object.defineProperty(GLTFFileLoaderExtension.prototype, "name", {
  1710. get: function () {
  1711. return this._name;
  1712. },
  1713. enumerable: true,
  1714. configurable: true
  1715. });
  1716. /**
  1717. * Defines an override for loading the runtime
  1718. * Return true to stop further extensions from loading the runtime
  1719. */
  1720. GLTFFileLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1721. return false;
  1722. };
  1723. /**
  1724. * Defines an override for loading buffers
  1725. * Return true to stop further extensions from loading this buffer
  1726. */
  1727. GLTFFileLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1728. return false;
  1729. };
  1730. /**
  1731. * Defines an override for loading texture buffers
  1732. * Return true to stop further extensions from loading this texture data
  1733. */
  1734. GLTFFileLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1735. return false;
  1736. };
  1737. /**
  1738. * Defines an override for creating textures
  1739. * Return true to stop further extensions from loading this texture
  1740. */
  1741. GLTFFileLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1742. return false;
  1743. };
  1744. /**
  1745. * Defines an override for loading shader strings
  1746. * Return true to stop further extensions from loading this shader data
  1747. */
  1748. GLTFFileLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1749. return false;
  1750. };
  1751. /**
  1752. * Defines an override for loading materials
  1753. * Return true to stop further extensions from loading this material
  1754. */
  1755. GLTFFileLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1756. return false;
  1757. };
  1758. // ---------
  1759. // Utilities
  1760. // ---------
  1761. GLTFFileLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1762. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1763. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  1764. }, function () {
  1765. setTimeout(function () {
  1766. onSuccess(BABYLON.GLTFFileLoaderBase.CreateRuntime(JSON.parse(data), scene, rootUrl));
  1767. });
  1768. });
  1769. };
  1770. GLTFFileLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1771. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1772. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError);
  1773. }, function () {
  1774. BABYLON.GLTFFileLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError);
  1775. });
  1776. };
  1777. GLTFFileLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  1778. GLTFFileLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFFileLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  1779. };
  1780. GLTFFileLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1781. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1782. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  1783. }, function () {
  1784. BABYLON.GLTFFileLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  1785. });
  1786. };
  1787. GLTFFileLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1788. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1789. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  1790. }, function () {
  1791. BABYLON.GLTFFileLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  1792. });
  1793. };
  1794. GLTFFileLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1795. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1796. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  1797. }, function () {
  1798. BABYLON.GLTFFileLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  1799. });
  1800. };
  1801. GLTFFileLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1802. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1803. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1804. }, function () {
  1805. BABYLON.GLTFFileLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1806. });
  1807. };
  1808. GLTFFileLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  1809. for (var extensionName in BABYLON.GLTFFileLoader.Extensions) {
  1810. var loaderExtension = BABYLON.GLTFFileLoader.Extensions[extensionName];
  1811. if (func(loaderExtension)) {
  1812. return;
  1813. }
  1814. }
  1815. defaultFunc();
  1816. };
  1817. return GLTFFileLoaderExtension;
  1818. }());
  1819. BABYLON.GLTFFileLoaderExtension = GLTFFileLoaderExtension;
  1820. })(BABYLON || (BABYLON = {}));
  1821. //# sourceMappingURL=../../src/glTF/babylon.glTFFileLoaderExtension.js.map
  1822. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  1823. var __extends = (this && this.__extends) || function (d, b) {
  1824. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  1825. function __() { this.constructor = d; }
  1826. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1827. };
  1828. var BABYLON;
  1829. (function (BABYLON) {
  1830. var BinaryExtensionBufferName = "binary_glTF";
  1831. var EContentFormat;
  1832. (function (EContentFormat) {
  1833. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  1834. })(EContentFormat || (EContentFormat = {}));
  1835. ;
  1836. ;
  1837. ;
  1838. ;
  1839. var GLTFBinaryExtension = (function (_super) {
  1840. __extends(GLTFBinaryExtension, _super);
  1841. function GLTFBinaryExtension() {
  1842. _super.call(this, "KHR_binary_glTF");
  1843. }
  1844. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1845. var _this = this;
  1846. if (!(data instanceof ArrayBuffer)) {
  1847. return false;
  1848. }
  1849. setTimeout(function () {
  1850. _this._binary = _this._parseBinary(data);
  1851. if (!_this._binary) {
  1852. onError();
  1853. return true;
  1854. }
  1855. var gltfRuntime = BABYLON.GLTFFileLoaderBase.CreateRuntime(_this._binary.content, scene, rootUrl);
  1856. if (gltfRuntime.extensionsUsed.indexOf(_this.name) === -1) {
  1857. BABYLON.Tools.Warn("glTF binary file does not have " + _this.name + " specified in extensionsUsed");
  1858. gltfRuntime.extensionsUsed.push(_this.name);
  1859. }
  1860. onSuccess(gltfRuntime);
  1861. });
  1862. return true;
  1863. };
  1864. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1865. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  1866. return false;
  1867. }
  1868. if (id !== BinaryExtensionBufferName) {
  1869. return false;
  1870. }
  1871. onSuccess(this._binary.body);
  1872. return true;
  1873. };
  1874. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1875. var texture = gltfRuntime.textures[id];
  1876. var source = gltfRuntime.images[texture.source];
  1877. if (!source.extensions || !(this.name in source.extensions)) {
  1878. return false;
  1879. }
  1880. var sourceExt = source.extensions[this.name];
  1881. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  1882. var buffer = BABYLON.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, BABYLON.EComponentType.UNSIGNED_BYTE);
  1883. onSuccess(buffer);
  1884. return true;
  1885. };
  1886. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1887. var shader = gltfRuntime.shaders[id];
  1888. if (!shader.extensions || !(this.name in shader.extensions)) {
  1889. return false;
  1890. }
  1891. var binaryExtensionShader = shader.extensions[this.name];
  1892. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  1893. var shaderBytes = BABYLON.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, BABYLON.EComponentType.UNSIGNED_BYTE);
  1894. setTimeout(function () {
  1895. var shaderString = BABYLON.GLTFUtils.DecodeBufferToText(shaderBytes);
  1896. onSuccess(shaderString);
  1897. });
  1898. return true;
  1899. };
  1900. // Parses a glTF binary array buffer into its content and body
  1901. GLTFBinaryExtension.prototype._parseBinary = function (data) {
  1902. var binaryReader = new BinaryReader(data);
  1903. var magic = BABYLON.GLTFUtils.DecodeBufferToText(binaryReader.getUint8Array(4));
  1904. if (magic != "glTF") {
  1905. BABYLON.Tools.Error("Unexpected magic: " + magic);
  1906. return null;
  1907. }
  1908. var version = binaryReader.getUint32();
  1909. if (version != 1) {
  1910. BABYLON.Tools.Error("Unsupported version: " + version);
  1911. return null;
  1912. }
  1913. var length = binaryReader.getUint32();
  1914. if (length != data.byteLength) {
  1915. BABYLON.Tools.Error("Length in header does not match actual data length: " + length + " != " + data.byteLength);
  1916. return null;
  1917. }
  1918. var contentLength = binaryReader.getUint32();
  1919. var contentFormat = binaryReader.getUint32();
  1920. var content;
  1921. switch (contentFormat) {
  1922. case EContentFormat.JSON:
  1923. var jsonText = BABYLON.GLTFUtils.DecodeBufferToText(binaryReader.getUint8Array(contentLength));
  1924. content = JSON.parse(jsonText);
  1925. break;
  1926. default:
  1927. BABYLON.Tools.Error("Unexpected content format: " + contentFormat);
  1928. return null;
  1929. }
  1930. var body = binaryReader.getUint8Array();
  1931. return {
  1932. content: content,
  1933. body: body
  1934. };
  1935. };
  1936. ;
  1937. return GLTFBinaryExtension;
  1938. }(BABYLON.GLTFFileLoaderExtension));
  1939. BABYLON.GLTFBinaryExtension = GLTFBinaryExtension;
  1940. var BinaryReader = (function () {
  1941. function BinaryReader(arrayBuffer) {
  1942. this._arrayBuffer = arrayBuffer;
  1943. this._dataView = new DataView(arrayBuffer);
  1944. this._byteOffset = 0;
  1945. }
  1946. BinaryReader.prototype.getUint32 = function () {
  1947. var value = this._dataView.getUint32(this._byteOffset, true);
  1948. this._byteOffset += 4;
  1949. return value;
  1950. };
  1951. BinaryReader.prototype.getUint8Array = function (length) {
  1952. if (!length) {
  1953. length = this._arrayBuffer.byteLength - this._byteOffset;
  1954. }
  1955. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  1956. this._byteOffset += length;
  1957. return value;
  1958. };
  1959. return BinaryReader;
  1960. }());
  1961. BABYLON.GLTFFileLoader.RegisterExtension(new GLTFBinaryExtension());
  1962. })(BABYLON || (BABYLON = {}));
  1963. //# sourceMappingURL=../../src/glTF/babylon.glTFBinaryExtension.js.map