babylon.glTF2FileLoader.js 122 KB

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