babylon.glTF2FileLoader.js 129 KB

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