babylon.glTF2FileLoader.js 131 KB

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