babylon.glTF2FileLoader.js 126 KB

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