babylon.glTF2FileLoader.js 111 KB

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