babylon.glTF2FileLoader.js 85 KB

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