babylon.glTF2FileLoader.js 134 KB

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