babylon.glTF2FileLoader.js 105 KB

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