babylon.glTF2FileLoader.js 105 KB

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