babylon.glTF2FileLoader.js 123 KB

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