babylon.glTF2FileLoader.js 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885
  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 = /** @class */ (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 = /** @class */ (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 = /** @class */ (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 = /** @class */ (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. var _this = this;
  591. node.babylonMesh.name = node.babylonMesh.name || mesh.name;
  592. if (!mesh.primitives || mesh.primitives.length === 0) {
  593. throw new Error(context + ": Primitives are missing");
  594. }
  595. this._createMorphTargets(context, node, mesh);
  596. this._loadAllVertexDataAsync(context, mesh, function () {
  597. _this._loadMorphTargets(context, node, mesh);
  598. var primitives = mesh.primitives;
  599. var vertexData = new BABYLON.VertexData();
  600. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  601. var primitive = primitives_1[_i];
  602. vertexData.merge(primitive.vertexData);
  603. }
  604. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  605. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  606. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  607. node.babylonMesh.subMeshes = [];
  608. var verticesStart = 0;
  609. var indicesStart = 0;
  610. for (var index = 0; index < primitives.length; index++) {
  611. var vertexData = primitives[index].vertexData;
  612. var verticesCount = vertexData.positions.length;
  613. var indicesCount = vertexData.indices.length;
  614. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  615. verticesStart += verticesCount;
  616. indicesStart += indicesCount;
  617. }
  618. ;
  619. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, _this._babylonScene);
  620. node.babylonMesh.material = multiMaterial;
  621. var subMaterials = multiMaterial.subMaterials;
  622. for (var index = 0; index < primitives.length; index++) {
  623. var primitive = primitives[index];
  624. if (primitive.material == null) {
  625. subMaterials[index] = _this._getDefaultMaterial();
  626. }
  627. else {
  628. var material = GLTF2.GLTFUtils.GetArrayItem(_this._gltf.materials, primitive.material);
  629. if (!material) {
  630. throw new Error(context + ": Failed to find material " + primitive.material);
  631. }
  632. _this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  633. if (isNew && _this._parent.onMaterialLoaded) {
  634. _this._parent.onMaterialLoaded(babylonMaterial);
  635. }
  636. if (_this._parent.onBeforeMaterialReadyAsync) {
  637. _this._addLoaderPendingData(material);
  638. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, node.babylonMesh, subMaterials[index] != null, function () {
  639. subMaterials[index] = babylonMaterial;
  640. _this._removeLoaderPendingData(material);
  641. });
  642. }
  643. else {
  644. subMaterials[index] = babylonMaterial;
  645. }
  646. });
  647. }
  648. }
  649. ;
  650. });
  651. };
  652. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  653. var primitives = mesh.primitives;
  654. var numRemainingPrimitives = primitives.length;
  655. var _loop_1 = function () {
  656. var primitive = primitives[index];
  657. this_1._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  658. primitive.vertexData = vertexData;
  659. if (--numRemainingPrimitives === 0) {
  660. onSuccess();
  661. }
  662. });
  663. };
  664. var this_1 = this;
  665. for (var index = 0; index < primitives.length; index++) {
  666. _loop_1();
  667. }
  668. };
  669. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  670. var _this = this;
  671. var attributes = primitive.attributes;
  672. if (!attributes) {
  673. throw new Error(context + ": Attributes are missing");
  674. }
  675. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  676. // TODO: handle other primitive modes
  677. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  678. }
  679. var vertexData = new BABYLON.VertexData();
  680. var numRemainingAttributes = Object.keys(attributes).length;
  681. var _loop_2 = function (attribute) {
  682. accessor = GLTF2.GLTFUtils.GetArrayItem(this_2._gltf.accessors, attributes[attribute]);
  683. if (!accessor) {
  684. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  685. }
  686. this_2._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  687. switch (attribute) {
  688. case "NORMAL":
  689. vertexData.normals = data;
  690. break;
  691. case "POSITION":
  692. vertexData.positions = data;
  693. break;
  694. case "TANGENT":
  695. vertexData.tangents = data;
  696. break;
  697. case "TEXCOORD_0":
  698. vertexData.uvs = data;
  699. break;
  700. case "TEXCOORD_1":
  701. vertexData.uvs2 = data;
  702. break;
  703. case "JOINTS_0":
  704. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  705. break;
  706. case "WEIGHTS_0":
  707. vertexData.matricesWeights = data;
  708. break;
  709. case "COLOR_0":
  710. vertexData.colors = data;
  711. break;
  712. default:
  713. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  714. break;
  715. }
  716. if (--numRemainingAttributes === 0) {
  717. if (primitive.indices == null) {
  718. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  719. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  720. onSuccess(vertexData);
  721. }
  722. else {
  723. var indicesAccessor = GLTF2.GLTFUtils.GetArrayItem(_this._gltf.accessors, primitive.indices);
  724. if (!indicesAccessor) {
  725. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  726. }
  727. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  728. vertexData.indices = data;
  729. onSuccess(vertexData);
  730. });
  731. }
  732. }
  733. });
  734. };
  735. var this_2 = this, accessor;
  736. for (var attribute in attributes) {
  737. _loop_2(attribute);
  738. }
  739. };
  740. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  741. var primitives = mesh.primitives;
  742. var targets = primitives[0].targets;
  743. if (!targets) {
  744. return;
  745. }
  746. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  747. var primitive = primitives_2[_i];
  748. if (!primitive.targets || primitive.targets.length != targets.length) {
  749. throw new Error(context + ": All primitives are required to list the same number of targets");
  750. }
  751. }
  752. var morphTargetManager = new BABYLON.MorphTargetManager();
  753. node.babylonMesh.morphTargetManager = morphTargetManager;
  754. for (var index = 0; index < targets.length; index++) {
  755. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  756. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  757. }
  758. };
  759. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  760. var morphTargetManager = node.babylonMesh.morphTargetManager;
  761. if (!morphTargetManager) {
  762. return;
  763. }
  764. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  765. var numTargets = morphTargetManager.numTargets;
  766. for (var index = 0; index < numTargets; index++) {
  767. var vertexData = new BABYLON.VertexData();
  768. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  769. var primitive = _a[_i];
  770. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  771. }
  772. var target = morphTargetManager.getTarget(index);
  773. target.setNormals(vertexData.normals);
  774. target.setPositions(vertexData.positions);
  775. target.setTangents(vertexData.tangents);
  776. }
  777. });
  778. };
  779. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  780. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  781. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  782. var primitive = _a[_i];
  783. var targets = primitive.targets;
  784. primitive.targetsVertexData = new Array(targets.length);
  785. var _loop_3 = function (index) {
  786. this_3._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  787. primitive.targetsVertexData[index] = vertexData;
  788. if (--numRemainingTargets === 0) {
  789. onSuccess();
  790. }
  791. });
  792. };
  793. var this_3 = this;
  794. for (var index = 0; index < targets.length; index++) {
  795. _loop_3(index);
  796. }
  797. }
  798. };
  799. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  800. var targetVertexData = new BABYLON.VertexData();
  801. var numRemainingAttributes = Object.keys(attributes).length;
  802. var _loop_4 = function (attribute) {
  803. accessor = GLTF2.GLTFUtils.GetArrayItem(this_4._gltf.accessors, attributes[attribute]);
  804. if (!accessor) {
  805. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  806. }
  807. this_4._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  808. // glTF stores morph target information as deltas while babylon.js expects the final data.
  809. // As a result we have to add the original data to the delta to calculate the final data.
  810. var values = data;
  811. switch (attribute) {
  812. case "NORMAL":
  813. for (var i = 0; i < values.length; i++) {
  814. values[i] += vertexData.normals[i];
  815. }
  816. targetVertexData.normals = values;
  817. break;
  818. case "POSITION":
  819. for (var i = 0; i < values.length; i++) {
  820. values[i] += vertexData.positions[i];
  821. }
  822. targetVertexData.positions = values;
  823. break;
  824. case "TANGENT":
  825. // Tangent data for morph targets is stored as xyz delta.
  826. // The vertexData.tangent is stored as xyzw.
  827. // So we need to skip every fourth vertexData.tangent.
  828. for (var i = 0, j = 0; i < values.length; i++, j++) {
  829. values[i] += vertexData.tangents[j];
  830. if ((i + 1) % 3 == 0) {
  831. j++;
  832. }
  833. }
  834. targetVertexData.tangents = values;
  835. break;
  836. default:
  837. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  838. break;
  839. }
  840. if (--numRemainingAttributes === 0) {
  841. onSuccess(targetVertexData);
  842. }
  843. });
  844. };
  845. var this_4 = this, accessor;
  846. for (var attribute in attributes) {
  847. _loop_4(attribute);
  848. }
  849. };
  850. GLTFLoader.prototype._loadTransform = function (node) {
  851. var position = BABYLON.Vector3.Zero();
  852. var rotation = BABYLON.Quaternion.Identity();
  853. var scaling = BABYLON.Vector3.One();
  854. if (node.matrix) {
  855. var mat = BABYLON.Matrix.FromArray(node.matrix);
  856. mat.decompose(scaling, rotation, position);
  857. }
  858. else {
  859. if (node.translation)
  860. position = BABYLON.Vector3.FromArray(node.translation);
  861. if (node.rotation)
  862. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  863. if (node.scale)
  864. scaling = BABYLON.Vector3.FromArray(node.scale);
  865. }
  866. node.babylonMesh.position = position;
  867. node.babylonMesh.rotationQuaternion = rotation;
  868. node.babylonMesh.scaling = scaling;
  869. };
  870. GLTFLoader.prototype._loadSkin = function (context, skin) {
  871. var _this = this;
  872. var skeletonId = "skeleton" + skin.index;
  873. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  874. if (skin.inverseBindMatrices == null) {
  875. this._loadBones(context, skin, null);
  876. }
  877. else {
  878. var accessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, skin.inverseBindMatrices);
  879. if (!accessor) {
  880. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  881. }
  882. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  883. _this._loadBones(context, skin, data);
  884. });
  885. }
  886. return skin.babylonSkeleton;
  887. };
  888. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  889. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  890. node.babylonBones = node.babylonBones || {};
  891. node.babylonBones[skin.index] = babylonBone;
  892. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  893. node.babylonAnimationTargets.push(babylonBone);
  894. return babylonBone;
  895. };
  896. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  897. var babylonBones = {};
  898. for (var i = 0; i < skin.joints.length; i++) {
  899. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, skin.joints[i]);
  900. if (!node) {
  901. throw new Error(context + ": Failed to find joint " + skin.joints[i]);
  902. }
  903. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  904. }
  905. };
  906. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  907. var babylonBone = babylonBones[node.index];
  908. if (babylonBone) {
  909. return babylonBone;
  910. }
  911. var boneIndex = skin.joints.indexOf(node.index);
  912. var baseMatrix = BABYLON.Matrix.Identity();
  913. if (inverseBindMatrixData && boneIndex !== -1) {
  914. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  915. baseMatrix.invertToRef(baseMatrix);
  916. }
  917. var babylonParentBone;
  918. if (node.index !== skin.skeleton && node.parent !== this._rootNode) {
  919. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  920. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  921. }
  922. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  923. babylonBones[node.index] = babylonBone;
  924. return babylonBone;
  925. };
  926. GLTFLoader.prototype._getNodeMatrix = function (node) {
  927. return node.matrix ?
  928. BABYLON.Matrix.FromArray(node.matrix) :
  929. 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());
  930. };
  931. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  932. if (parentNode === void 0) { parentNode = null; }
  933. for (var i = 0; i < indices.length; i++) {
  934. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, indices[i]);
  935. if (!node) {
  936. throw new Error(context + ": Failed to find node " + indices[i]);
  937. }
  938. this._traverseNode(context, node, action, parentNode);
  939. }
  940. };
  941. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  942. if (parentNode === void 0) { parentNode = null; }
  943. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  944. return;
  945. }
  946. if (!action(node, parentNode)) {
  947. return;
  948. }
  949. if (node.children) {
  950. this._traverseNodes(context, node.children, action, node);
  951. }
  952. };
  953. GLTFLoader.prototype._loadAnimations = function () {
  954. var animations = this._gltf.animations;
  955. if (!animations) {
  956. return;
  957. }
  958. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  959. var animation = animations[animationIndex];
  960. var context = "#/animations/" + animationIndex;
  961. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  962. var channel = GLTF2.GLTFUtils.GetArrayItem(animation.channels, channelIndex);
  963. if (!channel) {
  964. throw new Error(context + ": Failed to find channel " + channelIndex);
  965. }
  966. var sampler = GLTF2.GLTFUtils.GetArrayItem(animation.samplers, channel.sampler);
  967. if (!sampler) {
  968. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  969. }
  970. this._loadAnimationChannel(animation, context + "/channels/" + channelIndex, channel, context + "/samplers/" + channel.sampler, sampler);
  971. }
  972. }
  973. };
  974. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  975. var targetNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, channel.target.node);
  976. if (!targetNode) {
  977. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  978. }
  979. var targetPath;
  980. var animationType;
  981. switch (channel.target.path) {
  982. case "translation":
  983. targetPath = "position";
  984. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  985. break;
  986. case "rotation":
  987. targetPath = "rotationQuaternion";
  988. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  989. break;
  990. case "scale":
  991. targetPath = "scaling";
  992. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  993. break;
  994. case "weights":
  995. targetPath = "influence";
  996. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  997. break;
  998. default:
  999. throw new Error(channelContext + ": Invalid target path '" + channel.target.path + "'");
  1000. }
  1001. var inputData;
  1002. var outputData;
  1003. var checkSuccess = function () {
  1004. if (!inputData || !outputData) {
  1005. return;
  1006. }
  1007. var outputBufferOffset = 0;
  1008. var getNextOutputValue;
  1009. switch (targetPath) {
  1010. case "position":
  1011. getNextOutputValue = function () {
  1012. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  1013. outputBufferOffset += 3;
  1014. return value;
  1015. };
  1016. break;
  1017. case "rotationQuaternion":
  1018. getNextOutputValue = function () {
  1019. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  1020. outputBufferOffset += 4;
  1021. return value;
  1022. };
  1023. break;
  1024. case "scaling":
  1025. getNextOutputValue = function () {
  1026. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  1027. outputBufferOffset += 3;
  1028. return value;
  1029. };
  1030. break;
  1031. case "influence":
  1032. getNextOutputValue = function () {
  1033. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  1034. var value = new Array(numTargets);
  1035. for (var i = 0; i < numTargets; i++) {
  1036. value[i] = outputData[outputBufferOffset++];
  1037. }
  1038. return value;
  1039. };
  1040. break;
  1041. }
  1042. var getNextKey;
  1043. switch (sampler.interpolation) {
  1044. case "LINEAR":
  1045. getNextKey = function (frameIndex) { return ({
  1046. frame: inputData[frameIndex],
  1047. value: getNextOutputValue()
  1048. }); };
  1049. break;
  1050. case "CUBICSPLINE":
  1051. getNextKey = function (frameIndex) { return ({
  1052. frame: inputData[frameIndex],
  1053. inTangent: getNextOutputValue(),
  1054. value: getNextOutputValue(),
  1055. outTangent: getNextOutputValue()
  1056. }); };
  1057. break;
  1058. default:
  1059. throw new Error(samplerContext + ": Invalid interpolation '" + sampler.interpolation + "'");
  1060. }
  1061. ;
  1062. var keys = new Array(inputData.length);
  1063. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  1064. keys[frameIndex] = getNextKey(frameIndex);
  1065. }
  1066. animation.targets = animation.targets || [];
  1067. if (targetPath === "influence") {
  1068. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  1069. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  1070. var morphTarget = morphTargetManager.getTarget(targetIndex);
  1071. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  1072. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1073. babylonAnimation.setKeys(keys.map(function (key) { return ({
  1074. frame: key.frame,
  1075. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  1076. value: key.value[targetIndex],
  1077. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  1078. }); }));
  1079. morphTarget.animations.push(babylonAnimation);
  1080. animation.targets.push(morphTarget);
  1081. }
  1082. }
  1083. else {
  1084. var animationName = animation.name || "anim" + animation.index;
  1085. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1086. babylonAnimation.setKeys(keys);
  1087. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  1088. var target = targetNode.babylonAnimationTargets[i];
  1089. target.animations.push(babylonAnimation.clone());
  1090. animation.targets.push(target);
  1091. }
  1092. }
  1093. };
  1094. var inputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.input);
  1095. if (!inputAccessor) {
  1096. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  1097. }
  1098. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  1099. inputData = data;
  1100. checkSuccess();
  1101. });
  1102. var outputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.output);
  1103. if (!outputAccessor) {
  1104. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  1105. }
  1106. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  1107. outputData = data;
  1108. checkSuccess();
  1109. });
  1110. };
  1111. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  1112. var _this = this;
  1113. this._addPendingData(buffer);
  1114. if (buffer.loadedData) {
  1115. onSuccess(buffer.loadedData);
  1116. this._removePendingData(buffer);
  1117. }
  1118. else if (buffer.loadedObservable) {
  1119. buffer.loadedObservable.add(function (buffer) {
  1120. onSuccess(buffer.loadedData);
  1121. _this._removePendingData(buffer);
  1122. });
  1123. }
  1124. else {
  1125. if (!buffer.uri) {
  1126. throw new Error(context + ": Uri is missing");
  1127. }
  1128. if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  1129. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  1130. buffer.loadedData = new Uint8Array(data);
  1131. onSuccess(buffer.loadedData);
  1132. this._removePendingData(buffer);
  1133. }
  1134. else {
  1135. if (!GLTF2.GLTFUtils.ValidateUri(buffer.uri)) {
  1136. throw new Error(context + ": Uri '" + buffer.uri + "' is invalid");
  1137. }
  1138. buffer.loadedObservable = new BABYLON.Observable();
  1139. buffer.loadedObservable.add(function (buffer) {
  1140. onSuccess(buffer.loadedData);
  1141. _this._removePendingData(buffer);
  1142. });
  1143. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  1144. _this._tryCatchOnError(function () {
  1145. buffer.loadedData = new Uint8Array(data);
  1146. buffer.loadedObservable.notifyObservers(buffer);
  1147. buffer.loadedObservable = null;
  1148. });
  1149. }, function (event) {
  1150. _this._tryCatchOnError(function () {
  1151. _this._onProgress(event);
  1152. });
  1153. }, this._babylonScene.database, true, function (request) {
  1154. _this._tryCatchOnError(function () {
  1155. throw new Error(context + ": Failed to load '" + buffer.uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  1156. });
  1157. });
  1158. }
  1159. }
  1160. };
  1161. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  1162. var _this = this;
  1163. var buffer = GLTF2.GLTFUtils.GetArrayItem(this._gltf.buffers, bufferView.buffer);
  1164. if (!buffer) {
  1165. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  1166. }
  1167. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  1168. if (_this._disposed) {
  1169. return;
  1170. }
  1171. try {
  1172. var data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  1173. }
  1174. catch (e) {
  1175. throw new Error(context + ": " + e.message);
  1176. }
  1177. onSuccess(data);
  1178. });
  1179. };
  1180. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  1181. var _this = this;
  1182. if (accessor.sparse) {
  1183. throw new Error(context + ": Sparse accessors are not currently supported");
  1184. }
  1185. if (accessor.normalized) {
  1186. throw new Error(context + ": Normalized accessors are not currently supported");
  1187. }
  1188. var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, accessor.bufferView);
  1189. if (!bufferView) {
  1190. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  1191. }
  1192. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  1193. var numComponents = _this._getNumComponentsOfType(accessor.type);
  1194. if (numComponents === 0) {
  1195. throw new Error(context + ": Invalid type (" + accessor.type + ")");
  1196. }
  1197. var data;
  1198. switch (accessor.componentType) {
  1199. case GLTF2.EComponentType.BYTE:
  1200. data = _this._buildArrayBuffer(Float32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  1201. break;
  1202. case GLTF2.EComponentType.UNSIGNED_BYTE:
  1203. data = _this._buildArrayBuffer(Uint8Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  1204. break;
  1205. case GLTF2.EComponentType.SHORT:
  1206. data = _this._buildArrayBuffer(Int16Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  1207. break;
  1208. case GLTF2.EComponentType.UNSIGNED_SHORT:
  1209. data = _this._buildArrayBuffer(Uint16Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  1210. break;
  1211. case GLTF2.EComponentType.UNSIGNED_INT:
  1212. data = _this._buildArrayBuffer(Uint32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  1213. break;
  1214. case GLTF2.EComponentType.FLOAT:
  1215. data = _this._buildArrayBuffer(Float32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  1216. break;
  1217. default:
  1218. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  1219. }
  1220. onSuccess(data);
  1221. });
  1222. };
  1223. GLTFLoader.prototype._getNumComponentsOfType = function (type) {
  1224. switch (type) {
  1225. case "SCALAR": return 1;
  1226. case "VEC2": return 2;
  1227. case "VEC3": return 3;
  1228. case "VEC4": return 4;
  1229. case "MAT2": return 4;
  1230. case "MAT3": return 9;
  1231. case "MAT4": return 16;
  1232. }
  1233. return 0;
  1234. };
  1235. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, context, data, byteOffset, count, numComponents, byteStride) {
  1236. try {
  1237. var byteOffset = data.byteOffset + (byteOffset || 0);
  1238. var targetLength = count * numComponents;
  1239. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  1240. return new typedArray(data.buffer, byteOffset, targetLength);
  1241. }
  1242. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  1243. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  1244. var targetBuffer = new typedArray(targetLength);
  1245. var sourceIndex = 0;
  1246. var targetIndex = 0;
  1247. while (targetIndex < targetLength) {
  1248. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  1249. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  1250. targetIndex++;
  1251. }
  1252. sourceIndex += elementStride;
  1253. }
  1254. return targetBuffer;
  1255. }
  1256. catch (e) {
  1257. throw new Error(context + ": " + e);
  1258. }
  1259. };
  1260. GLTFLoader.prototype._addPendingData = function (data) {
  1261. if (!this._renderReady) {
  1262. this._renderPendingCount++;
  1263. }
  1264. this._addLoaderPendingData(data);
  1265. };
  1266. GLTFLoader.prototype._removePendingData = function (data) {
  1267. if (!this._renderReady) {
  1268. if (--this._renderPendingCount === 0) {
  1269. this._renderReady = true;
  1270. this._onRenderReady();
  1271. }
  1272. }
  1273. this._removeLoaderPendingData(data);
  1274. };
  1275. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  1276. this._loaderPendingCount++;
  1277. this._loaderTrackers.forEach(function (tracker) { return tracker._addPendingData(data); });
  1278. };
  1279. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  1280. this._loaderTrackers.forEach(function (tracker) { return tracker._removePendingData(data); });
  1281. if (--this._loaderPendingCount === 0) {
  1282. this._onComplete();
  1283. }
  1284. };
  1285. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  1286. var _this = this;
  1287. var tracker = new GLTFLoaderTracker(function () {
  1288. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker));
  1289. onComplete();
  1290. });
  1291. this._loaderTrackers.push(tracker);
  1292. this._addLoaderPendingData(tracker);
  1293. action();
  1294. this._removeLoaderPendingData(tracker);
  1295. };
  1296. GLTFLoader.prototype._getDefaultMaterial = function () {
  1297. if (!this._defaultMaterial) {
  1298. var id = "__gltf_default";
  1299. var material = this._babylonScene.getMaterialByName(id);
  1300. if (!material) {
  1301. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  1302. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1303. material.metallic = 1;
  1304. material.roughness = 1;
  1305. }
  1306. this._defaultMaterial = material;
  1307. }
  1308. return this._defaultMaterial;
  1309. };
  1310. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  1311. var babylonMaterial = material.babylonMaterial;
  1312. // Ensure metallic workflow
  1313. babylonMaterial.metallic = 1;
  1314. babylonMaterial.roughness = 1;
  1315. var properties = material.pbrMetallicRoughness;
  1316. if (!properties) {
  1317. return;
  1318. }
  1319. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  1320. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  1321. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  1322. if (properties.baseColorTexture) {
  1323. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.baseColorTexture.index);
  1324. if (!texture) {
  1325. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  1326. }
  1327. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  1328. }
  1329. if (properties.metallicRoughnessTexture) {
  1330. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.metallicRoughnessTexture.index);
  1331. if (!texture) {
  1332. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  1333. }
  1334. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  1335. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1336. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1337. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1338. }
  1339. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  1340. };
  1341. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  1342. if (material.babylonMaterial) {
  1343. assign(material.babylonMaterial, false);
  1344. return;
  1345. }
  1346. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  1347. return;
  1348. }
  1349. this._createPbrMaterial(material);
  1350. this._loadMaterialBaseProperties(context, material);
  1351. this._loadMaterialMetallicRoughnessProperties(context, material);
  1352. assign(material.babylonMaterial, true);
  1353. };
  1354. GLTFLoader.prototype._createPbrMaterial = function (material) {
  1355. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  1356. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1357. material.babylonMaterial = babylonMaterial;
  1358. };
  1359. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  1360. var babylonMaterial = material.babylonMaterial;
  1361. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  1362. if (material.doubleSided) {
  1363. babylonMaterial.backFaceCulling = false;
  1364. babylonMaterial.twoSidedLighting = true;
  1365. }
  1366. if (material.normalTexture) {
  1367. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.normalTexture.index);
  1368. if (!texture) {
  1369. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  1370. }
  1371. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  1372. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  1373. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  1374. if (material.normalTexture.scale != null) {
  1375. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1376. }
  1377. }
  1378. if (material.occlusionTexture) {
  1379. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.occlusionTexture.index);
  1380. if (!texture) {
  1381. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  1382. }
  1383. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  1384. babylonMaterial.useAmbientInGrayScale = true;
  1385. if (material.occlusionTexture.strength != null) {
  1386. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1387. }
  1388. }
  1389. if (material.emissiveTexture) {
  1390. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.emissiveTexture.index);
  1391. if (!texture) {
  1392. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  1393. }
  1394. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  1395. }
  1396. };
  1397. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  1398. var babylonMaterial = material.babylonMaterial;
  1399. var alphaMode = material.alphaMode || "OPAQUE";
  1400. switch (alphaMode) {
  1401. case "OPAQUE":
  1402. // default is opaque
  1403. break;
  1404. case "MASK":
  1405. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  1406. if (colorFactor) {
  1407. if (colorFactor[3] == 0) {
  1408. babylonMaterial.alphaCutOff = 1;
  1409. }
  1410. else {
  1411. babylonMaterial.alphaCutOff /= colorFactor[3];
  1412. }
  1413. }
  1414. if (babylonMaterial.albedoTexture) {
  1415. babylonMaterial.albedoTexture.hasAlpha = true;
  1416. }
  1417. break;
  1418. case "BLEND":
  1419. if (colorFactor) {
  1420. babylonMaterial.alpha = colorFactor[3];
  1421. }
  1422. if (babylonMaterial.albedoTexture) {
  1423. babylonMaterial.albedoTexture.hasAlpha = true;
  1424. babylonMaterial.useAlphaFromAlbedoTexture = true;
  1425. }
  1426. break;
  1427. default:
  1428. throw new Error(context + ": Invalid alpha mode '" + material.alphaMode + "'");
  1429. }
  1430. };
  1431. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  1432. var _this = this;
  1433. var sampler = (texture.sampler == null ? {} : GLTF2.GLTFUtils.GetArrayItem(this._gltf.samplers, texture.sampler));
  1434. if (!sampler) {
  1435. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  1436. }
  1437. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  1438. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  1439. this._addPendingData(texture);
  1440. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  1441. _this._tryCatchOnError(function () {
  1442. _this._removePendingData(texture);
  1443. });
  1444. }, function (message) {
  1445. _this._tryCatchOnError(function () {
  1446. throw new Error(context + ": " + message);
  1447. });
  1448. });
  1449. if (texture.url) {
  1450. babylonTexture.updateURL(texture.url);
  1451. }
  1452. else if (texture.dataReadyObservable) {
  1453. texture.dataReadyObservable.add(function (texture) {
  1454. babylonTexture.updateURL(texture.url);
  1455. });
  1456. }
  1457. else {
  1458. texture.dataReadyObservable = new BABYLON.Observable();
  1459. texture.dataReadyObservable.add(function (texture) {
  1460. babylonTexture.updateURL(texture.url);
  1461. });
  1462. var image = GLTF2.GLTFUtils.GetArrayItem(this._gltf.images, texture.source);
  1463. if (!image) {
  1464. throw new Error(context + ": Failed to find source " + texture.source);
  1465. }
  1466. this._loadImage("#/images/" + image.index, image, function (data) {
  1467. texture.url = URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  1468. texture.dataReadyObservable.notifyObservers(texture);
  1469. });
  1470. }
  1471. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  1472. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  1473. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  1474. babylonTexture.name = texture.name || "texture" + texture.index;
  1475. if (this._parent.onTextureLoaded) {
  1476. this._parent.onTextureLoaded(babylonTexture);
  1477. }
  1478. return babylonTexture;
  1479. };
  1480. GLTFLoader.prototype._loadImage = function (context, image, onSuccess) {
  1481. var _this = this;
  1482. if (image.uri) {
  1483. if (!GLTF2.GLTFUtils.ValidateUri(image.uri)) {
  1484. throw new Error(context + ": Uri '" + image.uri + "' is invalid");
  1485. }
  1486. if (GLTF2.GLTFUtils.IsBase64(image.uri)) {
  1487. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(image.uri)));
  1488. }
  1489. else {
  1490. BABYLON.Tools.LoadFile(this._rootUrl + image.uri, function (data) {
  1491. _this._tryCatchOnError(function () {
  1492. onSuccess(data);
  1493. });
  1494. }, function (event) {
  1495. _this._tryCatchOnError(function () {
  1496. _this._onProgress(event);
  1497. });
  1498. }, this._babylonScene.database, true, function (request) {
  1499. _this._tryCatchOnError(function () {
  1500. throw new Error(context + ": Failed to load '" + image.uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  1501. });
  1502. });
  1503. }
  1504. }
  1505. else {
  1506. var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, image.bufferView);
  1507. if (!bufferView) {
  1508. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  1509. }
  1510. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  1511. }
  1512. };
  1513. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  1514. try {
  1515. handler();
  1516. }
  1517. catch (e) {
  1518. this._onError(e.message);
  1519. }
  1520. };
  1521. GLTFLoader.Extensions = {};
  1522. return GLTFLoader;
  1523. }());
  1524. GLTF2.GLTFLoader = GLTFLoader;
  1525. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  1526. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1527. })(BABYLON || (BABYLON = {}));
  1528. //# sourceMappingURL=babylon.glTFLoader.js.map
  1529. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1530. var BABYLON;
  1531. (function (BABYLON) {
  1532. var GLTF2;
  1533. (function (GLTF2) {
  1534. /**
  1535. * Utils functions for GLTF
  1536. */
  1537. var GLTFUtils = /** @class */ (function () {
  1538. function GLTFUtils() {
  1539. }
  1540. /**
  1541. * If the uri is a base64 string
  1542. * @param uri: the uri to test
  1543. */
  1544. GLTFUtils.IsBase64 = function (uri) {
  1545. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1546. };
  1547. /**
  1548. * Decode the base64 uri
  1549. * @param uri: the uri to decode
  1550. */
  1551. GLTFUtils.DecodeBase64 = function (uri) {
  1552. var decodedString = atob(uri.split(",")[1]);
  1553. var bufferLength = decodedString.length;
  1554. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1555. for (var i = 0; i < bufferLength; i++) {
  1556. bufferView[i] = decodedString.charCodeAt(i);
  1557. }
  1558. return bufferView.buffer;
  1559. };
  1560. GLTFUtils.ValidateUri = function (uri) {
  1561. return (uri.indexOf("..") === -1);
  1562. };
  1563. GLTFUtils.AssignIndices = function (array) {
  1564. if (array) {
  1565. for (var index = 0; index < array.length; index++) {
  1566. array[index].index = index;
  1567. }
  1568. }
  1569. };
  1570. GLTFUtils.GetArrayItem = function (array, index) {
  1571. if (!array || !array[index]) {
  1572. return null;
  1573. }
  1574. return array[index];
  1575. };
  1576. GLTFUtils.GetTextureWrapMode = function (mode) {
  1577. // Set defaults if undefined
  1578. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  1579. switch (mode) {
  1580. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1581. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1582. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1583. default:
  1584. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  1585. return BABYLON.Texture.WRAP_ADDRESSMODE;
  1586. }
  1587. };
  1588. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  1589. // Set defaults if undefined
  1590. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  1591. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  1592. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  1593. switch (minFilter) {
  1594. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  1595. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  1596. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  1597. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  1598. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  1599. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  1600. default:
  1601. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  1602. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  1603. }
  1604. }
  1605. else {
  1606. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  1607. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  1608. }
  1609. switch (minFilter) {
  1610. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  1611. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  1612. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  1613. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  1614. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  1615. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  1616. default:
  1617. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  1618. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  1619. }
  1620. }
  1621. };
  1622. return GLTFUtils;
  1623. }());
  1624. GLTF2.GLTFUtils = GLTFUtils;
  1625. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1626. })(BABYLON || (BABYLON = {}));
  1627. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  1628. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1629. var BABYLON;
  1630. (function (BABYLON) {
  1631. var GLTF2;
  1632. (function (GLTF2) {
  1633. var GLTFLoaderExtension = /** @class */ (function () {
  1634. function GLTFLoaderExtension() {
  1635. this.enabled = true;
  1636. }
  1637. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  1638. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  1639. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  1640. GLTFLoaderExtension.prototype._loadExtension = function (property, action) {
  1641. var _this = this;
  1642. if (!property.extensions) {
  1643. return false;
  1644. }
  1645. var extension = property.extensions[this.name];
  1646. if (!extension) {
  1647. return false;
  1648. }
  1649. // Clear out the extension before executing the action to avoid recursing into the same property.
  1650. property.extensions[this.name] = undefined;
  1651. action(extension, function () {
  1652. // Restore the extension after completing the action.
  1653. property.extensions[_this.name] = extension;
  1654. });
  1655. return true;
  1656. };
  1657. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  1658. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  1659. };
  1660. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  1661. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  1662. };
  1663. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  1664. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  1665. };
  1666. GLTFLoaderExtension._ApplyExtensions = function (action) {
  1667. var extensions = GLTFLoaderExtension._Extensions;
  1668. if (!extensions) {
  1669. return false;
  1670. }
  1671. for (var i = 0; i < extensions.length; i++) {
  1672. var extension = extensions[i];
  1673. if (extension.enabled && action(extension)) {
  1674. return true;
  1675. }
  1676. }
  1677. return false;
  1678. };
  1679. //
  1680. // Utilities
  1681. //
  1682. GLTFLoaderExtension._Extensions = [];
  1683. return GLTFLoaderExtension;
  1684. }());
  1685. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  1686. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1687. })(BABYLON || (BABYLON = {}));
  1688. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  1689. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  1690. var __extends = (this && this.__extends) || (function () {
  1691. var extendStatics = Object.setPrototypeOf ||
  1692. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1693. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1694. return function (d, b) {
  1695. extendStatics(d, b);
  1696. function __() { this.constructor = d; }
  1697. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1698. };
  1699. })();
  1700. var BABYLON;
  1701. (function (BABYLON) {
  1702. var GLTF2;
  1703. (function (GLTF2) {
  1704. var Extensions;
  1705. (function (Extensions) {
  1706. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  1707. var MSFTLOD = /** @class */ (function (_super) {
  1708. __extends(MSFTLOD, _super);
  1709. function MSFTLOD() {
  1710. return _super !== null && _super.apply(this, arguments) || this;
  1711. }
  1712. Object.defineProperty(MSFTLOD.prototype, "name", {
  1713. get: function () {
  1714. return "MSFT_lod";
  1715. },
  1716. enumerable: true,
  1717. configurable: true
  1718. });
  1719. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  1720. return this._loadExtension(node, function (extension, onComplete) {
  1721. for (var i = extension.ids.length - 1; i >= 0; i--) {
  1722. var lodNode = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.nodes, extension.ids[i]);
  1723. if (!lodNode) {
  1724. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  1725. }
  1726. loader._traverseNode(context, lodNode, action, parentNode);
  1727. }
  1728. loader._traverseNode(context, node, action, parentNode);
  1729. onComplete();
  1730. });
  1731. };
  1732. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  1733. var _this = this;
  1734. return this._loadExtension(node, function (extension, onComplete) {
  1735. var nodes = [node.index].concat(extension.ids).map(function (index) { return loader._gltf.nodes[index]; });
  1736. loader._addLoaderPendingData(node);
  1737. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  1738. loader._removeLoaderPendingData(node);
  1739. onComplete();
  1740. });
  1741. });
  1742. };
  1743. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  1744. var _this = this;
  1745. loader._whenAction(function () {
  1746. loader._loadNode(context, nodes[index]);
  1747. }, function () {
  1748. if (index !== nodes.length - 1) {
  1749. var previousNode = nodes[index + 1];
  1750. previousNode.babylonMesh.setEnabled(false);
  1751. }
  1752. if (index === 0) {
  1753. onComplete();
  1754. return;
  1755. }
  1756. setTimeout(function () {
  1757. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  1758. }, MSFTLOD.MinimalLODDelay);
  1759. });
  1760. };
  1761. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  1762. var _this = this;
  1763. return this._loadExtension(material, function (extension, onComplete) {
  1764. var materials = [material.index].concat(extension.ids).map(function (index) { return loader._gltf.materials[index]; });
  1765. loader._addLoaderPendingData(material);
  1766. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  1767. material.extensions[_this.name] = extension;
  1768. loader._removeLoaderPendingData(material);
  1769. onComplete();
  1770. });
  1771. });
  1772. };
  1773. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  1774. var _this = this;
  1775. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  1776. assign(babylonMaterial, isNew);
  1777. if (index === 0) {
  1778. onComplete();
  1779. return;
  1780. }
  1781. // Load the next LOD when the loader is ready to render and
  1782. // all active material textures of the current LOD are loaded.
  1783. loader._executeWhenRenderReady(function () {
  1784. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  1785. setTimeout(function () {
  1786. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  1787. }, MSFTLOD.MinimalLODDelay);
  1788. });
  1789. });
  1790. });
  1791. };
  1792. /**
  1793. * Specify the minimal delay between LODs in ms (default = 250)
  1794. */
  1795. MSFTLOD.MinimalLODDelay = 250;
  1796. return MSFTLOD;
  1797. }(GLTF2.GLTFLoaderExtension));
  1798. Extensions.MSFTLOD = MSFTLOD;
  1799. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  1800. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  1801. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1802. })(BABYLON || (BABYLON = {}));
  1803. //# sourceMappingURL=MSFT_lod.js.map
  1804. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  1805. var __extends = (this && this.__extends) || (function () {
  1806. var extendStatics = Object.setPrototypeOf ||
  1807. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1808. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1809. return function (d, b) {
  1810. extendStatics(d, b);
  1811. function __() { this.constructor = d; }
  1812. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1813. };
  1814. })();
  1815. var BABYLON;
  1816. (function (BABYLON) {
  1817. var GLTF2;
  1818. (function (GLTF2) {
  1819. var Extensions;
  1820. (function (Extensions) {
  1821. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  1822. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  1823. function KHRMaterialsPbrSpecularGlossiness() {
  1824. return _super !== null && _super.apply(this, arguments) || this;
  1825. }
  1826. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  1827. get: function () {
  1828. return "KHR_materials_pbrSpecularGlossiness";
  1829. },
  1830. enumerable: true,
  1831. configurable: true
  1832. });
  1833. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  1834. var _this = this;
  1835. return this._loadExtension(material, function (extension, onComplete) {
  1836. loader._createPbrMaterial(material);
  1837. loader._loadMaterialBaseProperties(context, material);
  1838. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  1839. assign(material.babylonMaterial, true);
  1840. });
  1841. };
  1842. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  1843. var babylonMaterial = material.babylonMaterial;
  1844. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  1845. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  1846. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  1847. if (properties.diffuseTexture) {
  1848. var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.diffuseTexture.index);
  1849. if (!texture) {
  1850. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  1851. }
  1852. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  1853. }
  1854. if (properties.specularGlossinessTexture) {
  1855. var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.specularGlossinessTexture.index);
  1856. if (!texture) {
  1857. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  1858. }
  1859. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  1860. babylonMaterial.reflectivityTexture.hasAlpha = true;
  1861. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  1862. }
  1863. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  1864. };
  1865. return KHRMaterialsPbrSpecularGlossiness;
  1866. }(GLTF2.GLTFLoaderExtension));
  1867. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  1868. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  1869. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  1870. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1871. })(BABYLON || (BABYLON = {}));
  1872. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map