babylon.glTF2FileLoader.js 114 KB

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