babylon.glTF2FileLoader.js 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. var GLTFLoaderCoordinateSystemMode;
  5. (function (GLTFLoaderCoordinateSystemMode) {
  6. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  7. // NOTE: When scene.useRightHandedSystem is false, an additional transform will be added to the root to transform the data from right-handed to left-handed.
  8. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  9. // The glTF right-handed data is not transformed in any form and is loaded directly.
  10. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  11. // Sets the useRightHandedSystem flag on the scene.
  12. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  13. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  14. var GLTFFileLoader = (function () {
  15. function GLTFFileLoader() {
  16. // V2 options
  17. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  18. this.name = "gltf";
  19. this.extensions = {
  20. ".gltf": { isBinary: false },
  21. ".glb": { isBinary: true }
  22. };
  23. }
  24. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  25. var loaderData = GLTFFileLoader._parse(data, onError);
  26. if (!loaderData) {
  27. return;
  28. }
  29. if (this.onParsed) {
  30. this.onParsed(loaderData);
  31. }
  32. var loader = this._getLoader(loaderData, onError);
  33. if (!loader) {
  34. return;
  35. }
  36. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  37. };
  38. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  39. var loaderData = GLTFFileLoader._parse(data, onError);
  40. if (!loaderData) {
  41. return;
  42. }
  43. if (this.onParsed) {
  44. this.onParsed(loaderData);
  45. }
  46. var loader = this._getLoader(loaderData, onError);
  47. if (!loader) {
  48. return;
  49. }
  50. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  51. };
  52. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  53. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  54. };
  55. GLTFFileLoader._parse = function (data, onError) {
  56. try {
  57. if (data instanceof ArrayBuffer) {
  58. return GLTFFileLoader._parseBinary(data, onError);
  59. }
  60. return {
  61. json: JSON.parse(data),
  62. bin: null
  63. };
  64. }
  65. catch (e) {
  66. onError(e.message);
  67. return null;
  68. }
  69. };
  70. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  71. var loaderVersion = { major: 2, minor: 0 };
  72. var asset = loaderData.json.asset || {};
  73. var version = GLTFFileLoader._parseVersion(asset.version);
  74. if (!version) {
  75. onError("Invalid version: " + asset.version);
  76. return null;
  77. }
  78. if (asset.minVersion !== undefined) {
  79. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  80. if (!minVersion) {
  81. onError("Invalid minimum version: " + asset.minVersion);
  82. return null;
  83. }
  84. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  85. onError("Incompatible minimum version: " + asset.minVersion);
  86. return null;
  87. }
  88. }
  89. var createLoaders = {
  90. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  91. 2: GLTFFileLoader.CreateGLTFLoaderV2
  92. };
  93. var createLoader = createLoaders[version.major];
  94. if (!createLoader) {
  95. onError("Unsupported version: " + asset.version);
  96. return null;
  97. }
  98. return createLoader(this);
  99. };
  100. GLTFFileLoader._parseBinary = function (data, onError) {
  101. var Binary = {
  102. Magic: 0x46546C67
  103. };
  104. var binaryReader = new BinaryReader(data);
  105. var magic = binaryReader.readUint32();
  106. if (magic !== Binary.Magic) {
  107. onError("Unexpected magic: " + magic);
  108. return null;
  109. }
  110. var version = binaryReader.readUint32();
  111. switch (version) {
  112. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  113. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  114. }
  115. onError("Unsupported version: " + version);
  116. return null;
  117. };
  118. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  119. var ContentFormat = {
  120. JSON: 0
  121. };
  122. var length = binaryReader.readUint32();
  123. if (length != binaryReader.getLength()) {
  124. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  125. return null;
  126. }
  127. var contentLength = binaryReader.readUint32();
  128. var contentFormat = binaryReader.readUint32();
  129. var content;
  130. switch (contentFormat) {
  131. case ContentFormat.JSON:
  132. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  133. break;
  134. default:
  135. onError("Unexpected content format: " + contentFormat);
  136. return null;
  137. }
  138. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  139. var body = binaryReader.readUint8Array(bytesRemaining);
  140. return {
  141. json: content,
  142. bin: body
  143. };
  144. };
  145. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  146. var ChunkFormat = {
  147. JSON: 0x4E4F534A,
  148. BIN: 0x004E4942
  149. };
  150. var length = binaryReader.readUint32();
  151. if (length !== binaryReader.getLength()) {
  152. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  153. return null;
  154. }
  155. // JSON chunk
  156. var chunkLength = binaryReader.readUint32();
  157. var chunkFormat = binaryReader.readUint32();
  158. if (chunkFormat !== ChunkFormat.JSON) {
  159. onError("First chunk format is not JSON");
  160. return null;
  161. }
  162. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  163. // Look for BIN chunk
  164. var bin = null;
  165. while (binaryReader.getPosition() < binaryReader.getLength()) {
  166. chunkLength = binaryReader.readUint32();
  167. chunkFormat = binaryReader.readUint32();
  168. switch (chunkFormat) {
  169. case ChunkFormat.JSON:
  170. onError("Unexpected JSON chunk");
  171. return null;
  172. case ChunkFormat.BIN:
  173. bin = binaryReader.readUint8Array(chunkLength);
  174. break;
  175. default:
  176. // ignore unrecognized chunkFormat
  177. binaryReader.skipBytes(chunkLength);
  178. break;
  179. }
  180. }
  181. return {
  182. json: json,
  183. bin: bin
  184. };
  185. };
  186. GLTFFileLoader._parseVersion = function (version) {
  187. var match = (version + "").match(/^(\d+)\.(\d+)$/);
  188. if (!match) {
  189. return null;
  190. }
  191. return {
  192. major: parseInt(match[1]),
  193. minor: parseInt(match[2])
  194. };
  195. };
  196. GLTFFileLoader._compareVersion = function (a, b) {
  197. if (a.major > b.major)
  198. return 1;
  199. if (a.major < b.major)
  200. return -1;
  201. if (a.minor > b.minor)
  202. return 1;
  203. if (a.minor < b.minor)
  204. return -1;
  205. return 0;
  206. };
  207. GLTFFileLoader._decodeBufferToText = function (buffer) {
  208. var result = "";
  209. var length = buffer.byteLength;
  210. for (var i = 0; i < length; ++i) {
  211. result += String.fromCharCode(buffer[i]);
  212. }
  213. return result;
  214. };
  215. // V1 options
  216. GLTFFileLoader.HomogeneousCoordinates = false;
  217. GLTFFileLoader.IncrementalLoading = true;
  218. return GLTFFileLoader;
  219. }());
  220. BABYLON.GLTFFileLoader = GLTFFileLoader;
  221. var BinaryReader = (function () {
  222. function BinaryReader(arrayBuffer) {
  223. this._arrayBuffer = arrayBuffer;
  224. this._dataView = new DataView(arrayBuffer);
  225. this._byteOffset = 0;
  226. }
  227. BinaryReader.prototype.getPosition = function () {
  228. return this._byteOffset;
  229. };
  230. BinaryReader.prototype.getLength = function () {
  231. return this._arrayBuffer.byteLength;
  232. };
  233. BinaryReader.prototype.readUint32 = function () {
  234. var value = this._dataView.getUint32(this._byteOffset, true);
  235. this._byteOffset += 4;
  236. return value;
  237. };
  238. BinaryReader.prototype.readUint8Array = function (length) {
  239. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  240. this._byteOffset += length;
  241. return value;
  242. };
  243. BinaryReader.prototype.skipBytes = function (length) {
  244. this._byteOffset += length;
  245. };
  246. return BinaryReader;
  247. }());
  248. if (BABYLON.SceneLoader) {
  249. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  250. }
  251. })(BABYLON || (BABYLON = {}));
  252. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  253. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  254. var BABYLON;
  255. (function (BABYLON) {
  256. var GLTF2;
  257. (function (GLTF2) {
  258. /**
  259. * Enums
  260. */
  261. var EComponentType;
  262. (function (EComponentType) {
  263. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  264. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  265. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  266. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  267. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  268. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  269. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  270. var EMeshPrimitiveMode;
  271. (function (EMeshPrimitiveMode) {
  272. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  273. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  274. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  275. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  276. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  277. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  278. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  279. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  280. var ETextureMagFilter;
  281. (function (ETextureMagFilter) {
  282. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  283. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  284. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  285. var ETextureMinFilter;
  286. (function (ETextureMinFilter) {
  287. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  288. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  289. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  290. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  291. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  292. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  293. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  294. var ETextureWrapMode;
  295. (function (ETextureWrapMode) {
  296. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  297. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  298. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  299. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  300. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  301. })(BABYLON || (BABYLON = {}));
  302. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  303. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  304. var BABYLON;
  305. (function (BABYLON) {
  306. var GLTF2;
  307. (function (GLTF2) {
  308. var GLTFLoaderTracker = (function () {
  309. function GLTFLoaderTracker(onComplete) {
  310. this._pendingCount = 0;
  311. this._callback = onComplete;
  312. }
  313. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  314. this._pendingCount++;
  315. };
  316. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  317. if (--this._pendingCount === 0) {
  318. this._callback();
  319. }
  320. };
  321. return GLTFLoaderTracker;
  322. }());
  323. var GLTFLoader = (function () {
  324. function GLTFLoader(parent) {
  325. this._renderReady = false;
  326. this._disposed = false;
  327. this._renderReadyObservable = new BABYLON.Observable();
  328. // Count of pending work that needs to complete before the asset is rendered.
  329. this._renderPendingCount = 0;
  330. // Count of pending work that needs to complete before the loader is disposed.
  331. this._loaderPendingCount = 0;
  332. this._loaderTrackers = new Array();
  333. this._parent = parent;
  334. }
  335. GLTFLoader.RegisterExtension = function (extension) {
  336. if (GLTFLoader.Extensions[extension.name]) {
  337. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  338. return;
  339. }
  340. GLTFLoader.Extensions[extension.name] = extension;
  341. // Keep the order of registration so that extensions registered first are called first.
  342. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  343. };
  344. GLTFLoader.prototype.dispose = function () {
  345. if (this._disposed) {
  346. return;
  347. }
  348. this._disposed = true;
  349. // Revoke object urls created during load
  350. if (this._gltf.textures) {
  351. this._gltf.textures.forEach(function (texture) {
  352. if (texture.url) {
  353. URL.revokeObjectURL(texture.url);
  354. }
  355. });
  356. }
  357. this._gltf = undefined;
  358. this._babylonScene = undefined;
  359. this._rootUrl = undefined;
  360. this._defaultMaterial = undefined;
  361. this._successCallback = undefined;
  362. this._errorCallback = undefined;
  363. this._renderReady = false;
  364. this._renderReadyObservable.clear();
  365. this._renderPendingCount = 0;
  366. this._loaderPendingCount = 0;
  367. };
  368. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  369. var _this = this;
  370. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  371. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  372. }, onProgress, onError);
  373. };
  374. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  375. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  376. };
  377. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  378. var _this = this;
  379. this._tryCatchOnError(function () {
  380. _this._loadData(data);
  381. _this._babylonScene = scene;
  382. _this._rootUrl = rootUrl;
  383. _this._successCallback = onSuccess;
  384. _this._progressCallback = onProgress;
  385. _this._errorCallback = onError;
  386. GLTF2.GLTFUtils.AssignIndices(_this._gltf.accessors);
  387. GLTF2.GLTFUtils.AssignIndices(_this._gltf.animations);
  388. GLTF2.GLTFUtils.AssignIndices(_this._gltf.buffers);
  389. GLTF2.GLTFUtils.AssignIndices(_this._gltf.bufferViews);
  390. GLTF2.GLTFUtils.AssignIndices(_this._gltf.images);
  391. GLTF2.GLTFUtils.AssignIndices(_this._gltf.materials);
  392. GLTF2.GLTFUtils.AssignIndices(_this._gltf.meshes);
  393. GLTF2.GLTFUtils.AssignIndices(_this._gltf.nodes);
  394. GLTF2.GLTFUtils.AssignIndices(_this._gltf.scenes);
  395. GLTF2.GLTFUtils.AssignIndices(_this._gltf.skins);
  396. GLTF2.GLTFUtils.AssignIndices(_this._gltf.textures);
  397. _this._addPendingData(_this);
  398. _this._loadDefaultScene(nodeNames);
  399. _this._loadAnimations();
  400. _this._removePendingData(_this);
  401. });
  402. };
  403. GLTFLoader.prototype._onError = function (message) {
  404. if (this._disposed) {
  405. return;
  406. }
  407. BABYLON.Tools.Error("glTF Loader: " + message);
  408. if (this._errorCallback) {
  409. this._errorCallback(message);
  410. }
  411. this.dispose();
  412. };
  413. GLTFLoader.prototype._onProgress = function (event) {
  414. if (this._disposed) {
  415. return;
  416. }
  417. if (this._progressCallback) {
  418. this._progressCallback(event);
  419. }
  420. };
  421. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  422. if (this._renderReady) {
  423. func();
  424. }
  425. else {
  426. this._renderReadyObservable.add(func);
  427. }
  428. };
  429. GLTFLoader.prototype._onRenderReady = function () {
  430. this._rootNode.babylonMesh.setEnabled(true);
  431. this._startAnimations();
  432. this._successCallback();
  433. this._renderReadyObservable.notifyObservers(this);
  434. if (this._parent.onReady) {
  435. this._parent.onReady();
  436. }
  437. };
  438. GLTFLoader.prototype._onComplete = function () {
  439. if (this._parent.onComplete) {
  440. this._parent.onComplete();
  441. }
  442. this.dispose();
  443. };
  444. GLTFLoader.prototype._loadData = function (data) {
  445. this._gltf = data.json;
  446. if (data.bin) {
  447. var buffers = this._gltf.buffers;
  448. if (buffers && buffers[0] && !buffers[0].uri) {
  449. var binaryBuffer = buffers[0];
  450. if (binaryBuffer.byteLength != data.bin.byteLength) {
  451. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  452. }
  453. binaryBuffer.loadedData = data.bin;
  454. }
  455. else {
  456. BABYLON.Tools.Warn("Unexpected BIN chunk");
  457. }
  458. }
  459. };
  460. GLTFLoader.prototype._getMeshes = function () {
  461. var meshes = [this._rootNode.babylonMesh];
  462. var nodes = this._gltf.nodes;
  463. if (nodes) {
  464. nodes.forEach(function (node) {
  465. if (node.babylonMesh) {
  466. meshes.push(node.babylonMesh);
  467. }
  468. });
  469. }
  470. return meshes;
  471. };
  472. GLTFLoader.prototype._getSkeletons = function () {
  473. var skeletons = new Array();
  474. var skins = this._gltf.skins;
  475. if (skins) {
  476. skins.forEach(function (skin) {
  477. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  478. skeletons.push(skin.babylonSkeleton);
  479. }
  480. });
  481. }
  482. return skeletons;
  483. };
  484. GLTFLoader.prototype._getAnimationTargets = function () {
  485. var targets = new Array();
  486. var animations = this._gltf.animations;
  487. if (animations) {
  488. animations.forEach(function (animation) {
  489. targets.push.apply(targets, animation.targets);
  490. });
  491. }
  492. return targets;
  493. };
  494. GLTFLoader.prototype._startAnimations = function () {
  495. var _this = this;
  496. this._getAnimationTargets().forEach(function (target) { return _this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); });
  497. };
  498. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  499. var scene = GLTF2.GLTFUtils.GetArrayItem(this._gltf.scenes, this._gltf.scene || 0);
  500. if (!scene) {
  501. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  502. }
  503. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  504. };
  505. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  506. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  507. switch (this._parent.coordinateSystemMode) {
  508. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  509. if (!this._babylonScene.useRightHandedSystem) {
  510. this._rootNode.babylonMesh.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  511. this._rootNode.babylonMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  512. }
  513. break;
  514. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  515. // do nothing
  516. break;
  517. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  518. this._babylonScene.useRightHandedSystem = true;
  519. break;
  520. default:
  521. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  522. return;
  523. }
  524. var nodeIndices = scene.nodes;
  525. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  526. node.parent = parentNode;
  527. return true;
  528. }, this._rootNode);
  529. if (nodeNames) {
  530. if (!(nodeNames instanceof Array)) {
  531. nodeNames = [nodeNames];
  532. }
  533. var filteredNodeIndices = new Array();
  534. this._traverseNodes(context, nodeIndices, function (node) {
  535. if (nodeNames.indexOf(node.name) !== -1) {
  536. filteredNodeIndices.push(node.index);
  537. return false;
  538. }
  539. return true;
  540. }, this._rootNode);
  541. nodeIndices = filteredNodeIndices;
  542. }
  543. for (var i = 0; i < nodeIndices.length; i++) {
  544. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, nodeIndices[i]);
  545. if (!node) {
  546. throw new Error(context + ": Failed to find node " + nodeIndices[i]);
  547. }
  548. this._loadNode("#/nodes/" + nodeIndices[i], node);
  549. }
  550. // Disable the root mesh until the asset is ready to render.
  551. this._rootNode.babylonMesh.setEnabled(false);
  552. };
  553. GLTFLoader.prototype._loadNode = function (context, node) {
  554. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  555. return;
  556. }
  557. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  558. this._loadTransform(node);
  559. if (node.mesh != null) {
  560. var mesh = GLTF2.GLTFUtils.GetArrayItem(this._gltf.meshes, node.mesh);
  561. if (!mesh) {
  562. throw new Error(context + ": Failed to find mesh " + node.mesh);
  563. }
  564. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  565. }
  566. node.babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  567. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  568. node.babylonAnimationTargets.push(node.babylonMesh);
  569. if (node.skin != null) {
  570. var skin = GLTF2.GLTFUtils.GetArrayItem(this._gltf.skins, node.skin);
  571. if (!skin) {
  572. throw new Error(context + ": Failed to find skin " + node.skin);
  573. }
  574. node.babylonMesh.skeleton = this._loadSkin("#/skins/" + node.skin, skin);
  575. }
  576. if (node.camera != null) {
  577. // TODO: handle cameras
  578. }
  579. if (node.children) {
  580. for (var i = 0; i < node.children.length; i++) {
  581. var childNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, node.children[i]);
  582. if (!childNode) {
  583. throw new Error(context + ": Failed to find child node " + node.children[i]);
  584. }
  585. this._loadNode("#/nodes/" + node.children[i], childNode);
  586. }
  587. }
  588. };
  589. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  590. node.babylonMesh.name = mesh.name || node.babylonMesh.name;
  591. var babylonMultiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  592. node.babylonMesh.material = babylonMultiMaterial;
  593. var geometry = new BABYLON.Geometry(node.babylonMesh.name, this._babylonScene, null, false, node.babylonMesh);
  594. var vertexData = new BABYLON.VertexData();
  595. vertexData.positions = [];
  596. vertexData.indices = [];
  597. var subMeshInfos = [];
  598. var numRemainingPrimitives = mesh.primitives.length;
  599. for (var index = 0; index < mesh.primitives.length; index++) {
  600. var primitive = mesh.primitives[index];
  601. this._loadPrimitive(context + "/primitives/" + index, node, mesh, primitive, function (subVertexData, loadMaterial) {
  602. subMeshInfos.push({
  603. verticesStart: vertexData.positions.length,
  604. verticesCount: subVertexData.positions.length,
  605. indicesStart: vertexData.indices.length,
  606. indicesCount: subVertexData.indices.length,
  607. loadMaterial: loadMaterial
  608. });
  609. vertexData.merge(subVertexData);
  610. if (--numRemainingPrimitives === 0) {
  611. geometry.setAllVerticesData(vertexData, false);
  612. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  613. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  614. node.babylonMesh.subMeshes = [];
  615. for (var index = 0; index < subMeshInfos.length; index++) {
  616. var info = subMeshInfos[index];
  617. new BABYLON.SubMesh(index, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, node.babylonMesh);
  618. info.loadMaterial(index);
  619. }
  620. }
  621. });
  622. }
  623. };
  624. GLTFLoader.prototype._loadPrimitive = function (context, node, mesh, primitive, onSuccess) {
  625. var _this = this;
  626. var subMaterials = node.babylonMesh.material.subMaterials;
  627. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  628. // TODO: handle other primitive modes
  629. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  630. }
  631. this._createMorphTargets(node, mesh, primitive);
  632. this._loadVertexDataAsync(context, mesh, primitive, function (vertexData) {
  633. _this._loadMorphTargetsData(context, mesh, primitive, vertexData, node.babylonMesh);
  634. var loadMaterial = function (index) {
  635. if (primitive.material == null) {
  636. subMaterials[index] = _this._getDefaultMaterial();
  637. }
  638. else {
  639. var material = GLTF2.GLTFUtils.GetArrayItem(_this._gltf.materials, primitive.material);
  640. if (!material) {
  641. throw new Error(context + ": Failed to find material " + primitive.material);
  642. }
  643. _this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  644. if (isNew && _this._parent.onMaterialLoaded) {
  645. _this._parent.onMaterialLoaded(babylonMaterial);
  646. }
  647. if (_this._parent.onBeforeMaterialReadyAsync) {
  648. _this._addLoaderPendingData(material);
  649. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, node.babylonMesh, subMaterials[index] != null, function () {
  650. subMaterials[index] = babylonMaterial;
  651. _this._removeLoaderPendingData(material);
  652. });
  653. }
  654. else {
  655. subMaterials[index] = babylonMaterial;
  656. }
  657. });
  658. }
  659. };
  660. onSuccess(vertexData, loadMaterial);
  661. });
  662. };
  663. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  664. var _this = this;
  665. var attributes = primitive.attributes;
  666. if (!attributes) {
  667. throw new Error(context + ": Attributes are missing");
  668. }
  669. var vertexData = new BABYLON.VertexData();
  670. var numRemainingAttributes = Object.keys(attributes).length;
  671. var _loop_1 = function (attribute) {
  672. accessor = GLTF2.GLTFUtils.GetArrayItem(this_1._gltf.accessors, attributes[attribute]);
  673. if (!accessor) {
  674. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  675. }
  676. this_1._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  677. switch (attribute) {
  678. case "NORMAL":
  679. vertexData.normals = data;
  680. break;
  681. case "POSITION":
  682. vertexData.positions = data;
  683. break;
  684. case "TANGENT":
  685. vertexData.tangents = data;
  686. break;
  687. case "TEXCOORD_0":
  688. vertexData.uvs = data;
  689. break;
  690. case "TEXCOORD_1":
  691. vertexData.uvs2 = data;
  692. break;
  693. case "JOINTS_0":
  694. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  695. break;
  696. case "WEIGHTS_0":
  697. vertexData.matricesWeights = data;
  698. break;
  699. case "COLOR_0":
  700. vertexData.colors = data;
  701. break;
  702. default:
  703. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  704. break;
  705. }
  706. if (--numRemainingAttributes === 0) {
  707. if (primitive.indices == null) {
  708. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  709. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  710. onSuccess(vertexData);
  711. }
  712. else {
  713. var indicesAccessor = GLTF2.GLTFUtils.GetArrayItem(_this._gltf.accessors, primitive.indices);
  714. if (!indicesAccessor) {
  715. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  716. }
  717. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  718. vertexData.indices = data;
  719. onSuccess(vertexData);
  720. });
  721. }
  722. }
  723. });
  724. };
  725. var this_1 = this, accessor;
  726. for (var attribute in attributes) {
  727. _loop_1(attribute);
  728. }
  729. };
  730. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive) {
  731. var targets = primitive.targets;
  732. if (!targets) {
  733. return;
  734. }
  735. if (!node.babylonMesh.morphTargetManager) {
  736. node.babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  737. }
  738. for (var index = 0; index < targets.length; index++) {
  739. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  740. node.babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  741. }
  742. };
  743. GLTFLoader.prototype._loadMorphTargetsData = function (context, mesh, primitive, vertexData, babylonMesh) {
  744. var targets = primitive.targets;
  745. if (!targets) {
  746. return;
  747. }
  748. var _loop_2 = function () {
  749. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  750. attributes = targets[index];
  751. var _loop_3 = function (attribute) {
  752. accessor = GLTF2.GLTFUtils.GetArrayItem(this_2._gltf.accessors, attributes[attribute]);
  753. if (!accessor) {
  754. throw new Error(context + "/targets/" + index + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  755. }
  756. this_2._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  757. if (accessor.name) {
  758. babylonMorphTarget.name = accessor.name;
  759. }
  760. // glTF stores morph target information as deltas while babylon.js expects the final data.
  761. // As a result we have to add the original data to the delta to calculate the final data.
  762. var values = data;
  763. switch (attribute) {
  764. case "NORMAL":
  765. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.normals[i]; });
  766. babylonMorphTarget.setNormals(values);
  767. break;
  768. case "POSITION":
  769. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.positions[i]; });
  770. babylonMorphTarget.setPositions(values);
  771. break;
  772. case "TANGENT":
  773. // Tangent data for morph targets is stored as xyz delta.
  774. // The vertexData.tangent is stored as xyzw.
  775. // So we need to skip every fourth vertexData.tangent.
  776. for (var i = 0, j = 0; i < values.length; i++, j++) {
  777. values[i] += vertexData.tangents[j];
  778. if ((i + 1) % 3 == 0) {
  779. j++;
  780. }
  781. }
  782. babylonMorphTarget.setTangents(values);
  783. break;
  784. default:
  785. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  786. break;
  787. }
  788. });
  789. };
  790. for (var attribute in attributes) {
  791. _loop_3(attribute);
  792. }
  793. };
  794. var this_2 = this, attributes, accessor;
  795. for (var index = 0; index < targets.length; index++) {
  796. _loop_2();
  797. }
  798. };
  799. GLTFLoader.prototype._loadTransform = function (node) {
  800. var position = BABYLON.Vector3.Zero();
  801. var rotation = BABYLON.Quaternion.Identity();
  802. var scaling = BABYLON.Vector3.One();
  803. if (node.matrix) {
  804. var mat = BABYLON.Matrix.FromArray(node.matrix);
  805. mat.decompose(scaling, rotation, position);
  806. }
  807. else {
  808. if (node.translation)
  809. position = BABYLON.Vector3.FromArray(node.translation);
  810. if (node.rotation)
  811. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  812. if (node.scale)
  813. scaling = BABYLON.Vector3.FromArray(node.scale);
  814. }
  815. node.babylonMesh.position = position;
  816. node.babylonMesh.rotationQuaternion = rotation;
  817. node.babylonMesh.scaling = scaling;
  818. };
  819. GLTFLoader.prototype._loadSkin = function (context, skin) {
  820. var _this = this;
  821. var skeletonId = "skeleton" + skin.index;
  822. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  823. if (skin.inverseBindMatrices == null) {
  824. this._loadBones(context, skin, null);
  825. }
  826. else {
  827. var accessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, skin.inverseBindMatrices);
  828. if (!accessor) {
  829. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  830. }
  831. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  832. _this._loadBones(context, skin, data);
  833. });
  834. }
  835. return skin.babylonSkeleton;
  836. };
  837. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  838. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  839. node.babylonBones = node.babylonBones || {};
  840. node.babylonBones[skin.index] = babylonBone;
  841. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  842. node.babylonAnimationTargets.push(babylonBone);
  843. return babylonBone;
  844. };
  845. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  846. var babylonBones = {};
  847. for (var i = 0; i < skin.joints.length; i++) {
  848. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, skin.joints[i]);
  849. if (!node) {
  850. throw new Error(context + ": Failed to find joint " + skin.joints[i]);
  851. }
  852. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  853. }
  854. };
  855. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  856. var babylonBone = babylonBones[node.index];
  857. if (babylonBone) {
  858. return babylonBone;
  859. }
  860. var boneIndex = skin.joints.indexOf(node.index);
  861. var baseMatrix = BABYLON.Matrix.Identity();
  862. if (inverseBindMatrixData && boneIndex !== -1) {
  863. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  864. baseMatrix.invertToRef(baseMatrix);
  865. }
  866. var babylonParentBone;
  867. if (node.index !== skin.skeleton && node.parent !== this._rootNode) {
  868. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  869. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  870. }
  871. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  872. babylonBones[node.index] = babylonBone;
  873. return babylonBone;
  874. };
  875. GLTFLoader.prototype._getNodeMatrix = function (node) {
  876. return node.matrix ?
  877. BABYLON.Matrix.FromArray(node.matrix) :
  878. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  879. };
  880. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  881. if (parentNode === void 0) { parentNode = null; }
  882. for (var i = 0; i < indices.length; i++) {
  883. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, indices[i]);
  884. if (!node) {
  885. throw new Error(context + ": Failed to find node " + indices[i]);
  886. }
  887. this._traverseNode(context, node, action, parentNode);
  888. }
  889. };
  890. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  891. if (parentNode === void 0) { parentNode = null; }
  892. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  893. return;
  894. }
  895. if (!action(node, parentNode)) {
  896. return;
  897. }
  898. if (node.children) {
  899. this._traverseNodes(context, node.children, action, node);
  900. }
  901. };
  902. GLTFLoader.prototype._loadAnimations = function () {
  903. var animations = this._gltf.animations;
  904. if (!animations) {
  905. return;
  906. }
  907. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  908. var animation = animations[animationIndex];
  909. var context = "#/animations/" + animationIndex;
  910. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  911. var channel = GLTF2.GLTFUtils.GetArrayItem(animation.channels, channelIndex);
  912. if (!channel) {
  913. throw new Error(context + ": Failed to find channel " + channelIndex);
  914. }
  915. var sampler = GLTF2.GLTFUtils.GetArrayItem(animation.samplers, channel.sampler);
  916. if (!sampler) {
  917. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  918. }
  919. this._loadAnimationChannel(animation, context + "/channels/" + channelIndex, channel, context + "/samplers/" + channel.sampler, sampler);
  920. }
  921. }
  922. };
  923. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  924. var targetNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, channel.target.node);
  925. if (!targetNode) {
  926. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  927. }
  928. var targetPath;
  929. var animationType;
  930. switch (channel.target.path) {
  931. case "translation":
  932. targetPath = "position";
  933. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  934. break;
  935. case "rotation":
  936. targetPath = "rotationQuaternion";
  937. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  938. break;
  939. case "scale":
  940. targetPath = "scaling";
  941. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  942. break;
  943. case "weights":
  944. targetPath = "influence";
  945. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  946. break;
  947. default:
  948. throw new Error(channelContext + ": Invalid target path '" + channel.target.path + "'");
  949. }
  950. var inputData;
  951. var outputData;
  952. var checkSuccess = function () {
  953. if (!inputData || !outputData) {
  954. return;
  955. }
  956. var outputBufferOffset = 0;
  957. var getNextOutputValue;
  958. switch (targetPath) {
  959. case "position":
  960. getNextOutputValue = function () {
  961. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  962. outputBufferOffset += 3;
  963. return value;
  964. };
  965. break;
  966. case "rotationQuaternion":
  967. getNextOutputValue = function () {
  968. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  969. outputBufferOffset += 4;
  970. return value;
  971. };
  972. break;
  973. case "scaling":
  974. getNextOutputValue = function () {
  975. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  976. outputBufferOffset += 3;
  977. return value;
  978. };
  979. break;
  980. case "influence":
  981. getNextOutputValue = function () {
  982. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  983. var value = new Array(numTargets);
  984. for (var i = 0; i < numTargets; i++) {
  985. value[i] = outputData[outputBufferOffset++];
  986. }
  987. return value;
  988. };
  989. break;
  990. }
  991. var getNextKey;
  992. switch (sampler.interpolation) {
  993. case "LINEAR":
  994. getNextKey = function (frameIndex) { return ({
  995. frame: inputData[frameIndex],
  996. value: getNextOutputValue()
  997. }); };
  998. break;
  999. case "CUBICSPLINE":
  1000. getNextKey = function (frameIndex) { return ({
  1001. frame: inputData[frameIndex],
  1002. inTangent: getNextOutputValue(),
  1003. value: getNextOutputValue(),
  1004. outTangent: getNextOutputValue()
  1005. }); };
  1006. break;
  1007. default:
  1008. throw new Error(samplerContext + ": Invalid interpolation '" + sampler.interpolation + "'");
  1009. }
  1010. ;
  1011. var keys = new Array(inputData.length);
  1012. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  1013. keys[frameIndex] = getNextKey(frameIndex);
  1014. }
  1015. animation.targets = animation.targets || [];
  1016. if (targetPath === "influence") {
  1017. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  1018. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  1019. var morphTarget = morphTargetManager.getTarget(targetIndex);
  1020. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  1021. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1022. babylonAnimation.setKeys(keys.map(function (key) { return ({
  1023. frame: key.frame,
  1024. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  1025. value: key.value[targetIndex],
  1026. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  1027. }); }));
  1028. morphTarget.animations.push(babylonAnimation);
  1029. animation.targets.push(morphTarget);
  1030. }
  1031. }
  1032. else {
  1033. var animationName = animation.name || "anim" + animation.index;
  1034. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1035. babylonAnimation.setKeys(keys);
  1036. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  1037. var target = targetNode.babylonAnimationTargets[i];
  1038. target.animations.push(babylonAnimation.clone());
  1039. animation.targets.push(target);
  1040. }
  1041. }
  1042. };
  1043. var inputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.input);
  1044. if (!inputAccessor) {
  1045. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  1046. }
  1047. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  1048. inputData = data;
  1049. checkSuccess();
  1050. });
  1051. var outputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.output);
  1052. if (!outputAccessor) {
  1053. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  1054. }
  1055. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  1056. outputData = data;
  1057. checkSuccess();
  1058. });
  1059. };
  1060. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  1061. var _this = this;
  1062. this._addPendingData(buffer);
  1063. if (buffer.loadedData) {
  1064. onSuccess(buffer.loadedData);
  1065. this._removePendingData(buffer);
  1066. }
  1067. else if (buffer.loadedObservable) {
  1068. buffer.loadedObservable.add(function (buffer) {
  1069. onSuccess(buffer.loadedData);
  1070. _this._removePendingData(buffer);
  1071. });
  1072. }
  1073. else {
  1074. if (!buffer.uri) {
  1075. throw new Error(context + ": Uri is missing");
  1076. }
  1077. if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  1078. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  1079. buffer.loadedData = new Uint8Array(data);
  1080. onSuccess(buffer.loadedData);
  1081. this._removePendingData(buffer);
  1082. }
  1083. else {
  1084. if (!GLTF2.GLTFUtils.ValidateUri(buffer.uri)) {
  1085. throw new Error(context + ": Uri '" + buffer.uri + "' is invalid");
  1086. }
  1087. buffer.loadedObservable = new BABYLON.Observable();
  1088. buffer.loadedObservable.add(function (buffer) {
  1089. onSuccess(buffer.loadedData);
  1090. _this._removePendingData(buffer);
  1091. });
  1092. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  1093. _this._tryCatchOnError(function () {
  1094. buffer.loadedData = new Uint8Array(data);
  1095. buffer.loadedObservable.notifyObservers(buffer);
  1096. buffer.loadedObservable = null;
  1097. });
  1098. }, function (event) {
  1099. _this._tryCatchOnError(function () {
  1100. _this._onProgress(event);
  1101. });
  1102. }, this._babylonScene.database, true, function (request) {
  1103. _this._tryCatchOnError(function () {
  1104. throw new Error(context + ": Failed to load '" + buffer.uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  1105. });
  1106. });
  1107. }
  1108. }
  1109. };
  1110. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  1111. var _this = this;
  1112. var buffer = GLTF2.GLTFUtils.GetArrayItem(this._gltf.buffers, bufferView.buffer);
  1113. if (!buffer) {
  1114. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  1115. }
  1116. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  1117. if (_this._disposed) {
  1118. return;
  1119. }
  1120. try {
  1121. var data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  1122. }
  1123. catch (e) {
  1124. throw new Error(context + ": " + e.message);
  1125. }
  1126. onSuccess(data);
  1127. });
  1128. };
  1129. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  1130. var _this = this;
  1131. if (accessor.sparse) {
  1132. throw new Error(context + ": Sparse accessors are not currently supported");
  1133. }
  1134. if (accessor.normalized) {
  1135. throw new Error(context + ": Normalized accessors are not currently supported");
  1136. }
  1137. var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, accessor.bufferView);
  1138. if (!bufferView) {
  1139. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  1140. }
  1141. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  1142. var numComponents = _this._getNumComponentsOfType(accessor.type);
  1143. if (numComponents === 0) {
  1144. throw new Error(context + ": Invalid type (" + accessor.type + ")");
  1145. }
  1146. var data;
  1147. switch (accessor.componentType) {
  1148. case GLTF2.EComponentType.BYTE:
  1149. data = _this._buildArrayBuffer(Float32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  1150. break;
  1151. case GLTF2.EComponentType.UNSIGNED_BYTE:
  1152. data = _this._buildArrayBuffer(Uint8Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  1153. break;
  1154. case GLTF2.EComponentType.SHORT:
  1155. data = _this._buildArrayBuffer(Int16Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  1156. break;
  1157. case GLTF2.EComponentType.UNSIGNED_SHORT:
  1158. data = _this._buildArrayBuffer(Uint16Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  1159. break;
  1160. case GLTF2.EComponentType.UNSIGNED_INT:
  1161. data = _this._buildArrayBuffer(Uint32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  1162. break;
  1163. case GLTF2.EComponentType.FLOAT:
  1164. data = _this._buildArrayBuffer(Float32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  1165. break;
  1166. default:
  1167. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  1168. }
  1169. onSuccess(data);
  1170. });
  1171. };
  1172. GLTFLoader.prototype._getNumComponentsOfType = function (type) {
  1173. switch (type) {
  1174. case "SCALAR": return 1;
  1175. case "VEC2": return 2;
  1176. case "VEC3": return 3;
  1177. case "VEC4": return 4;
  1178. case "MAT2": return 4;
  1179. case "MAT3": return 9;
  1180. case "MAT4": return 16;
  1181. }
  1182. return 0;
  1183. };
  1184. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, context, data, byteOffset, count, numComponents, byteStride) {
  1185. try {
  1186. var byteOffset = data.byteOffset + (byteOffset || 0);
  1187. var targetLength = count * numComponents;
  1188. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  1189. return new typedArray(data.buffer, byteOffset, targetLength);
  1190. }
  1191. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  1192. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  1193. var targetBuffer = new typedArray(targetLength);
  1194. var sourceIndex = 0;
  1195. var targetIndex = 0;
  1196. while (targetIndex < targetLength) {
  1197. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  1198. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  1199. targetIndex++;
  1200. }
  1201. sourceIndex += elementStride;
  1202. }
  1203. return targetBuffer;
  1204. }
  1205. catch (e) {
  1206. throw new Error(context + ": " + e);
  1207. }
  1208. };
  1209. GLTFLoader.prototype._addPendingData = function (data) {
  1210. if (!this._renderReady) {
  1211. this._renderPendingCount++;
  1212. }
  1213. this._addLoaderPendingData(data);
  1214. };
  1215. GLTFLoader.prototype._removePendingData = function (data) {
  1216. if (!this._renderReady) {
  1217. if (--this._renderPendingCount === 0) {
  1218. this._renderReady = true;
  1219. this._onRenderReady();
  1220. }
  1221. }
  1222. this._removeLoaderPendingData(data);
  1223. };
  1224. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  1225. this._loaderPendingCount++;
  1226. this._loaderTrackers.forEach(function (tracker) { return tracker._addPendingData(data); });
  1227. };
  1228. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  1229. this._loaderTrackers.forEach(function (tracker) { return tracker._removePendingData(data); });
  1230. if (--this._loaderPendingCount === 0) {
  1231. this._onComplete();
  1232. }
  1233. };
  1234. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  1235. var _this = this;
  1236. var tracker = new GLTFLoaderTracker(function () {
  1237. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker));
  1238. onComplete();
  1239. });
  1240. this._loaderTrackers.push(tracker);
  1241. this._addLoaderPendingData(tracker);
  1242. action();
  1243. this._removeLoaderPendingData(tracker);
  1244. };
  1245. GLTFLoader.prototype._getDefaultMaterial = function () {
  1246. if (!this._defaultMaterial) {
  1247. var id = "__gltf_default";
  1248. var material = this._babylonScene.getMaterialByName(id);
  1249. if (!material) {
  1250. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  1251. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1252. material.metallic = 1;
  1253. material.roughness = 1;
  1254. }
  1255. this._defaultMaterial = material;
  1256. }
  1257. return this._defaultMaterial;
  1258. };
  1259. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  1260. var babylonMaterial = material.babylonMaterial;
  1261. // Ensure metallic workflow
  1262. babylonMaterial.metallic = 1;
  1263. babylonMaterial.roughness = 1;
  1264. var properties = material.pbrMetallicRoughness;
  1265. if (!properties) {
  1266. return;
  1267. }
  1268. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  1269. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  1270. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  1271. if (properties.baseColorTexture) {
  1272. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.baseColorTexture.index);
  1273. if (!texture) {
  1274. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  1275. }
  1276. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  1277. }
  1278. if (properties.metallicRoughnessTexture) {
  1279. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.metallicRoughnessTexture.index);
  1280. if (!texture) {
  1281. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  1282. }
  1283. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  1284. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1285. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1286. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1287. }
  1288. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  1289. };
  1290. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  1291. if (material.babylonMaterial) {
  1292. assign(material.babylonMaterial, false);
  1293. return;
  1294. }
  1295. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  1296. return;
  1297. }
  1298. this._createPbrMaterial(material);
  1299. this._loadMaterialBaseProperties(context, material);
  1300. this._loadMaterialMetallicRoughnessProperties(context, material);
  1301. assign(material.babylonMaterial, true);
  1302. };
  1303. GLTFLoader.prototype._createPbrMaterial = function (material) {
  1304. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  1305. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1306. material.babylonMaterial = babylonMaterial;
  1307. };
  1308. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  1309. var babylonMaterial = material.babylonMaterial;
  1310. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  1311. if (material.doubleSided) {
  1312. babylonMaterial.backFaceCulling = false;
  1313. babylonMaterial.twoSidedLighting = true;
  1314. }
  1315. if (material.normalTexture) {
  1316. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.normalTexture.index);
  1317. if (!texture) {
  1318. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  1319. }
  1320. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  1321. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  1322. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  1323. if (material.normalTexture.scale != null) {
  1324. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1325. }
  1326. }
  1327. if (material.occlusionTexture) {
  1328. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.occlusionTexture.index);
  1329. if (!texture) {
  1330. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  1331. }
  1332. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  1333. babylonMaterial.useAmbientInGrayScale = true;
  1334. if (material.occlusionTexture.strength != null) {
  1335. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1336. }
  1337. }
  1338. if (material.emissiveTexture) {
  1339. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.emissiveTexture.index);
  1340. if (!texture) {
  1341. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  1342. }
  1343. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  1344. }
  1345. };
  1346. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  1347. var babylonMaterial = material.babylonMaterial;
  1348. var alphaMode = material.alphaMode || "OPAQUE";
  1349. switch (alphaMode) {
  1350. case "OPAQUE":
  1351. // default is opaque
  1352. break;
  1353. case "MASK":
  1354. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  1355. if (colorFactor) {
  1356. if (colorFactor[3] == 0) {
  1357. babylonMaterial.alphaCutOff = 1;
  1358. }
  1359. else {
  1360. babylonMaterial.alphaCutOff /= colorFactor[3];
  1361. }
  1362. }
  1363. if (babylonMaterial.albedoTexture) {
  1364. babylonMaterial.albedoTexture.hasAlpha = true;
  1365. }
  1366. break;
  1367. case "BLEND":
  1368. if (colorFactor) {
  1369. babylonMaterial.alpha = colorFactor[3];
  1370. }
  1371. if (babylonMaterial.albedoTexture) {
  1372. babylonMaterial.albedoTexture.hasAlpha = true;
  1373. babylonMaterial.useAlphaFromAlbedoTexture = true;
  1374. }
  1375. break;
  1376. default:
  1377. throw new Error(context + ": Invalid alpha mode '" + material.alphaMode + "'");
  1378. }
  1379. };
  1380. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  1381. var _this = this;
  1382. var sampler = (texture.sampler == null ? {} : GLTF2.GLTFUtils.GetArrayItem(this._gltf.samplers, texture.sampler));
  1383. if (!sampler) {
  1384. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  1385. }
  1386. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  1387. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  1388. this._addPendingData(texture);
  1389. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  1390. _this._tryCatchOnError(function () {
  1391. _this._removePendingData(texture);
  1392. });
  1393. }, function (message) {
  1394. _this._tryCatchOnError(function () {
  1395. throw new Error(context + ": " + message);
  1396. });
  1397. });
  1398. if (texture.url) {
  1399. babylonTexture.updateURL(texture.url);
  1400. }
  1401. else if (texture.dataReadyObservable) {
  1402. texture.dataReadyObservable.add(function (texture) {
  1403. babylonTexture.updateURL(texture.url);
  1404. });
  1405. }
  1406. else {
  1407. texture.dataReadyObservable = new BABYLON.Observable();
  1408. texture.dataReadyObservable.add(function (texture) {
  1409. babylonTexture.updateURL(texture.url);
  1410. });
  1411. var image = GLTF2.GLTFUtils.GetArrayItem(this._gltf.images, texture.source);
  1412. if (!image) {
  1413. throw new Error(context + ": Failed to find source " + texture.source);
  1414. }
  1415. this._loadImage("#/images/" + image.index, image, function (data) {
  1416. texture.url = URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  1417. texture.dataReadyObservable.notifyObservers(texture);
  1418. });
  1419. }
  1420. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  1421. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  1422. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  1423. babylonTexture.name = texture.name || "texture" + texture.index;
  1424. if (this._parent.onTextureLoaded) {
  1425. this._parent.onTextureLoaded(babylonTexture);
  1426. }
  1427. return babylonTexture;
  1428. };
  1429. GLTFLoader.prototype._loadImage = function (context, image, onSuccess) {
  1430. var _this = this;
  1431. if (image.uri) {
  1432. if (!GLTF2.GLTFUtils.ValidateUri(image.uri)) {
  1433. throw new Error(context + ": Uri '" + image.uri + "' is invalid");
  1434. }
  1435. if (GLTF2.GLTFUtils.IsBase64(image.uri)) {
  1436. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(image.uri)));
  1437. }
  1438. else {
  1439. BABYLON.Tools.LoadFile(this._rootUrl + image.uri, function (data) {
  1440. _this._tryCatchOnError(function () {
  1441. onSuccess(data);
  1442. });
  1443. }, function (event) {
  1444. _this._tryCatchOnError(function () {
  1445. _this._onProgress(event);
  1446. });
  1447. }, this._babylonScene.database, true, function (request) {
  1448. _this._tryCatchOnError(function () {
  1449. throw new Error(context + ": Failed to load '" + image.uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  1450. });
  1451. });
  1452. }
  1453. }
  1454. else {
  1455. var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, image.bufferView);
  1456. if (!bufferView) {
  1457. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  1458. }
  1459. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  1460. }
  1461. };
  1462. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  1463. try {
  1464. handler();
  1465. }
  1466. catch (e) {
  1467. this._onError(e.message);
  1468. }
  1469. };
  1470. GLTFLoader.Extensions = {};
  1471. return GLTFLoader;
  1472. }());
  1473. GLTF2.GLTFLoader = GLTFLoader;
  1474. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  1475. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1476. })(BABYLON || (BABYLON = {}));
  1477. //# sourceMappingURL=babylon.glTFLoader.js.map
  1478. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1479. var BABYLON;
  1480. (function (BABYLON) {
  1481. var GLTF2;
  1482. (function (GLTF2) {
  1483. /**
  1484. * Utils functions for GLTF
  1485. */
  1486. var GLTFUtils = (function () {
  1487. function GLTFUtils() {
  1488. }
  1489. /**
  1490. * If the uri is a base64 string
  1491. * @param uri: the uri to test
  1492. */
  1493. GLTFUtils.IsBase64 = function (uri) {
  1494. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1495. };
  1496. /**
  1497. * Decode the base64 uri
  1498. * @param uri: the uri to decode
  1499. */
  1500. GLTFUtils.DecodeBase64 = function (uri) {
  1501. var decodedString = atob(uri.split(",")[1]);
  1502. var bufferLength = decodedString.length;
  1503. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1504. for (var i = 0; i < bufferLength; i++) {
  1505. bufferView[i] = decodedString.charCodeAt(i);
  1506. }
  1507. return bufferView.buffer;
  1508. };
  1509. GLTFUtils.ForEach = function (view, func) {
  1510. for (var index = 0; index < view.length; index++) {
  1511. func(view[index], index);
  1512. }
  1513. };
  1514. GLTFUtils.ValidateUri = function (uri) {
  1515. return (uri.indexOf("..") === -1);
  1516. };
  1517. GLTFUtils.AssignIndices = function (array) {
  1518. if (array) {
  1519. for (var index = 0; index < array.length; index++) {
  1520. array[index].index = index;
  1521. }
  1522. }
  1523. };
  1524. GLTFUtils.GetArrayItem = function (array, index) {
  1525. if (!array || !array[index]) {
  1526. return null;
  1527. }
  1528. return array[index];
  1529. };
  1530. GLTFUtils.GetTextureWrapMode = function (mode) {
  1531. // Set defaults if undefined
  1532. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  1533. switch (mode) {
  1534. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1535. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1536. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1537. default:
  1538. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  1539. return BABYLON.Texture.WRAP_ADDRESSMODE;
  1540. }
  1541. };
  1542. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  1543. // Set defaults if undefined
  1544. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  1545. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  1546. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  1547. switch (minFilter) {
  1548. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  1549. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  1550. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  1551. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  1552. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  1553. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  1554. default:
  1555. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  1556. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  1557. }
  1558. }
  1559. else {
  1560. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  1561. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  1562. }
  1563. switch (minFilter) {
  1564. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  1565. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  1566. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  1567. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  1568. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  1569. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  1570. default:
  1571. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  1572. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  1573. }
  1574. }
  1575. };
  1576. return GLTFUtils;
  1577. }());
  1578. GLTF2.GLTFUtils = GLTFUtils;
  1579. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1580. })(BABYLON || (BABYLON = {}));
  1581. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  1582. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1583. var BABYLON;
  1584. (function (BABYLON) {
  1585. var GLTF2;
  1586. (function (GLTF2) {
  1587. var GLTFLoaderExtension = (function () {
  1588. function GLTFLoaderExtension() {
  1589. this.enabled = true;
  1590. }
  1591. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  1592. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  1593. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  1594. GLTFLoaderExtension.prototype._loadExtension = function (property, action) {
  1595. var _this = this;
  1596. if (!property.extensions) {
  1597. return false;
  1598. }
  1599. var extension = property.extensions[this.name];
  1600. if (!extension) {
  1601. return false;
  1602. }
  1603. // Clear out the extension before executing the action to avoid recursing into the same property.
  1604. property.extensions[this.name] = undefined;
  1605. action(extension, function () {
  1606. // Restore the extension after completing the action.
  1607. property.extensions[_this.name] = extension;
  1608. });
  1609. return true;
  1610. };
  1611. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  1612. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  1613. };
  1614. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  1615. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  1616. };
  1617. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  1618. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  1619. };
  1620. GLTFLoaderExtension._ApplyExtensions = function (action) {
  1621. var extensions = GLTFLoaderExtension._Extensions;
  1622. if (!extensions) {
  1623. return false;
  1624. }
  1625. for (var i = 0; i < extensions.length; i++) {
  1626. var extension = extensions[i];
  1627. if (extension.enabled && action(extension)) {
  1628. return true;
  1629. }
  1630. }
  1631. return false;
  1632. };
  1633. //
  1634. // Utilities
  1635. //
  1636. GLTFLoaderExtension._Extensions = [];
  1637. return GLTFLoaderExtension;
  1638. }());
  1639. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  1640. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1641. })(BABYLON || (BABYLON = {}));
  1642. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  1643. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  1644. var __extends = (this && this.__extends) || (function () {
  1645. var extendStatics = Object.setPrototypeOf ||
  1646. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1647. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1648. return function (d, b) {
  1649. extendStatics(d, b);
  1650. function __() { this.constructor = d; }
  1651. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1652. };
  1653. })();
  1654. var BABYLON;
  1655. (function (BABYLON) {
  1656. var GLTF2;
  1657. (function (GLTF2) {
  1658. var Extensions;
  1659. (function (Extensions) {
  1660. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  1661. var MSFTLOD = (function (_super) {
  1662. __extends(MSFTLOD, _super);
  1663. function MSFTLOD() {
  1664. return _super !== null && _super.apply(this, arguments) || this;
  1665. }
  1666. Object.defineProperty(MSFTLOD.prototype, "name", {
  1667. get: function () {
  1668. return "MSFT_lod";
  1669. },
  1670. enumerable: true,
  1671. configurable: true
  1672. });
  1673. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  1674. return this._loadExtension(node, function (extension, onComplete) {
  1675. for (var i = extension.ids.length - 1; i >= 0; i--) {
  1676. var lodNode = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.nodes, extension.ids[i]);
  1677. if (!lodNode) {
  1678. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  1679. }
  1680. loader._traverseNode(context, lodNode, action, parentNode);
  1681. }
  1682. loader._traverseNode(context, node, action, parentNode);
  1683. onComplete();
  1684. });
  1685. };
  1686. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  1687. var _this = this;
  1688. return this._loadExtension(node, function (extension, onComplete) {
  1689. var nodes = [node.index].concat(extension.ids).map(function (index) { return loader._gltf.nodes[index]; });
  1690. loader._addLoaderPendingData(node);
  1691. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  1692. loader._removeLoaderPendingData(node);
  1693. onComplete();
  1694. });
  1695. });
  1696. };
  1697. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  1698. var _this = this;
  1699. loader._whenAction(function () {
  1700. loader._loadNode(context, nodes[index]);
  1701. }, function () {
  1702. if (index !== nodes.length - 1) {
  1703. var previousNode = nodes[index + 1];
  1704. previousNode.babylonMesh.setEnabled(false);
  1705. }
  1706. if (index === 0) {
  1707. onComplete();
  1708. return;
  1709. }
  1710. setTimeout(function () {
  1711. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  1712. }, MSFTLOD.MinimalLODDelay);
  1713. });
  1714. };
  1715. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  1716. var _this = this;
  1717. return this._loadExtension(material, function (extension, onComplete) {
  1718. var materials = [material.index].concat(extension.ids).map(function (index) { return loader._gltf.materials[index]; });
  1719. loader._addLoaderPendingData(material);
  1720. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  1721. material.extensions[_this.name] = extension;
  1722. loader._removeLoaderPendingData(material);
  1723. onComplete();
  1724. });
  1725. });
  1726. };
  1727. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  1728. var _this = this;
  1729. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  1730. assign(babylonMaterial, isNew);
  1731. if (index === 0) {
  1732. onComplete();
  1733. return;
  1734. }
  1735. // Load the next LOD when the loader is ready to render and
  1736. // all active material textures of the current LOD are loaded.
  1737. loader._executeWhenRenderReady(function () {
  1738. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  1739. setTimeout(function () {
  1740. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  1741. }, MSFTLOD.MinimalLODDelay);
  1742. });
  1743. });
  1744. });
  1745. };
  1746. /**
  1747. * Specify the minimal delay between LODs in ms (default = 250)
  1748. */
  1749. MSFTLOD.MinimalLODDelay = 250;
  1750. return MSFTLOD;
  1751. }(GLTF2.GLTFLoaderExtension));
  1752. Extensions.MSFTLOD = MSFTLOD;
  1753. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  1754. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  1755. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1756. })(BABYLON || (BABYLON = {}));
  1757. //# sourceMappingURL=MSFT_lod.js.map
  1758. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  1759. var __extends = (this && this.__extends) || (function () {
  1760. var extendStatics = Object.setPrototypeOf ||
  1761. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1762. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1763. return function (d, b) {
  1764. extendStatics(d, b);
  1765. function __() { this.constructor = d; }
  1766. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1767. };
  1768. })();
  1769. var BABYLON;
  1770. (function (BABYLON) {
  1771. var GLTF2;
  1772. (function (GLTF2) {
  1773. var Extensions;
  1774. (function (Extensions) {
  1775. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  1776. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  1777. function KHRMaterialsPbrSpecularGlossiness() {
  1778. return _super !== null && _super.apply(this, arguments) || this;
  1779. }
  1780. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  1781. get: function () {
  1782. return "KHR_materials_pbrSpecularGlossiness";
  1783. },
  1784. enumerable: true,
  1785. configurable: true
  1786. });
  1787. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  1788. var _this = this;
  1789. return this._loadExtension(material, function (extension, onComplete) {
  1790. loader._createPbrMaterial(material);
  1791. loader._loadMaterialBaseProperties(context, material);
  1792. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  1793. assign(material.babylonMaterial, true);
  1794. });
  1795. };
  1796. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  1797. var babylonMaterial = material.babylonMaterial;
  1798. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  1799. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  1800. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  1801. if (properties.diffuseTexture) {
  1802. var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.diffuseTexture.index);
  1803. if (!texture) {
  1804. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  1805. }
  1806. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  1807. }
  1808. if (properties.specularGlossinessTexture) {
  1809. var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.specularGlossinessTexture.index);
  1810. if (!texture) {
  1811. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  1812. }
  1813. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  1814. babylonMaterial.reflectivityTexture.hasAlpha = true;
  1815. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  1816. }
  1817. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  1818. };
  1819. return KHRMaterialsPbrSpecularGlossiness;
  1820. }(GLTF2.GLTFLoaderExtension));
  1821. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  1822. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  1823. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  1824. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1825. })(BABYLON || (BABYLON = {}));
  1826. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map