babylon.glTF2FileLoader.js 183 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960
  1. (function webpackUniversalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory(require("babylonjs"));
  4. else if(typeof define === 'function' && define.amd)
  5. define("babylonjs-loaders", ["babylonjs"], factory);
  6. else if(typeof exports === 'object')
  7. exports["babylonjs-loaders"] = factory(require("babylonjs"));
  8. else
  9. root["LOADERS"] = factory(root["BABYLON"]);
  10. })(window, function(__WEBPACK_EXTERNAL_MODULE_babylonjs__) {
  11. return /******/ (function(modules) { // webpackBootstrap
  12. /******/ // The module cache
  13. /******/ var installedModules = {};
  14. /******/
  15. /******/ // The require function
  16. /******/ function __webpack_require__(moduleId) {
  17. /******/
  18. /******/ // Check if module is in cache
  19. /******/ if(installedModules[moduleId]) {
  20. /******/ return installedModules[moduleId].exports;
  21. /******/ }
  22. /******/ // Create a new module (and put it into the cache)
  23. /******/ var module = installedModules[moduleId] = {
  24. /******/ i: moduleId,
  25. /******/ l: false,
  26. /******/ exports: {}
  27. /******/ };
  28. /******/
  29. /******/ // Execute the module function
  30. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  31. /******/
  32. /******/ // Flag the module as loaded
  33. /******/ module.l = true;
  34. /******/
  35. /******/ // Return the exports of the module
  36. /******/ return module.exports;
  37. /******/ }
  38. /******/
  39. /******/
  40. /******/ // expose the modules object (__webpack_modules__)
  41. /******/ __webpack_require__.m = modules;
  42. /******/
  43. /******/ // expose the module cache
  44. /******/ __webpack_require__.c = installedModules;
  45. /******/
  46. /******/ // define getter function for harmony exports
  47. /******/ __webpack_require__.d = function(exports, name, getter) {
  48. /******/ if(!__webpack_require__.o(exports, name)) {
  49. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  50. /******/ }
  51. /******/ };
  52. /******/
  53. /******/ // define __esModule on exports
  54. /******/ __webpack_require__.r = function(exports) {
  55. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  56. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  57. /******/ }
  58. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  59. /******/ };
  60. /******/
  61. /******/ // create a fake namespace object
  62. /******/ // mode & 1: value is a module id, require it
  63. /******/ // mode & 2: merge all properties of value into the ns
  64. /******/ // mode & 4: return value when already ns object
  65. /******/ // mode & 8|1: behave like require
  66. /******/ __webpack_require__.t = function(value, mode) {
  67. /******/ if(mode & 1) value = __webpack_require__(value);
  68. /******/ if(mode & 8) return value;
  69. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  70. /******/ var ns = Object.create(null);
  71. /******/ __webpack_require__.r(ns);
  72. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  73. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  74. /******/ return ns;
  75. /******/ };
  76. /******/
  77. /******/ // getDefaultExport function for compatibility with non-harmony modules
  78. /******/ __webpack_require__.n = function(module) {
  79. /******/ var getter = module && module.__esModule ?
  80. /******/ function getDefault() { return module['default']; } :
  81. /******/ function getModuleExports() { return module; };
  82. /******/ __webpack_require__.d(getter, 'a', getter);
  83. /******/ return getter;
  84. /******/ };
  85. /******/
  86. /******/ // Object.prototype.hasOwnProperty.call
  87. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  88. /******/
  89. /******/ // __webpack_public_path__
  90. /******/ __webpack_require__.p = "";
  91. /******/
  92. /******/
  93. /******/ // Load entry module and return exports
  94. /******/ return __webpack_require__(__webpack_require__.s = "./legacy/legacy-glTF2FileLoader.ts");
  95. /******/ })
  96. /************************************************************************/
  97. /******/ ({
  98. /***/ "../node_modules/webpack/buildin/global.js":
  99. /*!*************************************************!*\
  100. !*** ../node_modules/webpack/buildin/global.js ***!
  101. \*************************************************/
  102. /*! no static exports found */
  103. /***/ (function(module, exports) {
  104. var g;
  105. // This works in non-strict mode
  106. g = (function() {
  107. return this;
  108. })();
  109. try {
  110. // This works if eval is allowed (see CSP)
  111. g = g || Function("return this")() || (1, eval)("this");
  112. } catch (e) {
  113. // This works if the window reference is available
  114. if (typeof window === "object") g = window;
  115. }
  116. // g can still be undefined, but nothing to do about it...
  117. // We return undefined, instead of nothing here, so it's
  118. // easier to handle this case. if(!global) { ...}
  119. module.exports = g;
  120. /***/ }),
  121. /***/ "./legacy/legacy-glTF2FileLoader.ts":
  122. /*!******************************************!*\
  123. !*** ./legacy/legacy-glTF2FileLoader.ts ***!
  124. \******************************************/
  125. /*! no static exports found */
  126. /***/ (function(module, exports, __webpack_require__) {
  127. "use strict";
  128. /* WEBPACK VAR INJECTION */(function(global) {
  129. function __export(m) {
  130. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  131. }
  132. Object.defineProperty(exports, "__esModule", { value: true });
  133. var FileLoader = __webpack_require__(/*! ../src/glTF/glTFFileLoader */ "./src/glTF/glTFFileLoader.ts");
  134. var LoadersV2 = __webpack_require__(/*! ../src/glTF/2.0 */ "./src/glTF/2.0/index.ts");
  135. /**
  136. * This is the entry point for the UMD module.
  137. * The entry point for a future ESM package should be index.ts
  138. */
  139. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined);
  140. if (typeof globalObject !== "undefined") {
  141. globalObject.BABYLON = globalObject.BABYLON || {};
  142. for (var key in FileLoader) {
  143. globalObject.BABYLON[key] = FileLoader[key];
  144. }
  145. for (var key in LoadersV2) {
  146. globalObject.BABYLON[key] = LoadersV2[key];
  147. }
  148. }
  149. __export(__webpack_require__(/*! ../src/glTF/glTFFileLoader */ "./src/glTF/glTFFileLoader.ts"));
  150. __export(__webpack_require__(/*! ../src/glTF/2.0 */ "./src/glTF/2.0/index.ts"));
  151. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/global.js */ "../node_modules/webpack/buildin/global.js")))
  152. /***/ }),
  153. /***/ "./src/glTF/2.0/Extensions/EXT_lights_image_based.ts":
  154. /*!***********************************************************!*\
  155. !*** ./src/glTF/2.0/Extensions/EXT_lights_image_based.ts ***!
  156. \***********************************************************/
  157. /*! no static exports found */
  158. /***/ (function(module, exports, __webpack_require__) {
  159. "use strict";
  160. Object.defineProperty(exports, "__esModule", { value: true });
  161. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  162. var glTF2Loader_1 = __webpack_require__(/*! ../glTF2Loader */ "./src/glTF/2.0/glTF2Loader.ts");
  163. var NAME = "EXT_lights_image_based";
  164. /**
  165. * [Specification](https://github.com/KhronosGroup/glTF/blob/eb3e32332042e04691a5f35103f8c261e50d8f1e/extensions/2.0/Khronos/EXT_lights_image_based/README.md) (Experimental)
  166. */
  167. var EXT_lights_image_based = /** @class */ (function () {
  168. /** @hidden */
  169. function EXT_lights_image_based(loader) {
  170. /** The name of this extension. */
  171. this.name = NAME;
  172. /** Defines whether this extension is enabled. */
  173. this.enabled = true;
  174. this._loader = loader;
  175. }
  176. /** @hidden */
  177. EXT_lights_image_based.prototype.dispose = function () {
  178. delete this._loader;
  179. delete this._lights;
  180. };
  181. /** @hidden */
  182. EXT_lights_image_based.prototype.onLoading = function () {
  183. var extensions = this._loader.gltf.extensions;
  184. if (extensions && extensions[this.name]) {
  185. var extension = extensions[this.name];
  186. this._lights = extension.lights;
  187. }
  188. };
  189. /** @hidden */
  190. EXT_lights_image_based.prototype.loadSceneAsync = function (context, scene) {
  191. var _this = this;
  192. return glTF2Loader_1.GLTF2Loader.LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) {
  193. var promises = new Array();
  194. promises.push(_this._loader.loadSceneAsync(context, scene));
  195. _this._loader.logOpen("" + extensionContext);
  196. var light = glTF2Loader_1.ArrayItem.Get(extensionContext + "/light", _this._lights, extension.light);
  197. promises.push(_this._loadLightAsync("#/extensions/" + _this.name + "/lights/" + extension.light, light).then(function (texture) {
  198. _this._loader.babylonScene.environmentTexture = texture;
  199. }));
  200. _this._loader.logClose();
  201. return Promise.all(promises).then(function () { });
  202. });
  203. };
  204. EXT_lights_image_based.prototype._loadLightAsync = function (context, light) {
  205. var _this = this;
  206. if (!light._loaded) {
  207. var promises = new Array();
  208. this._loader.logOpen("" + context);
  209. var imageData_1 = new Array(light.specularImages.length);
  210. var _loop_1 = function (mipmap) {
  211. var faces = light.specularImages[mipmap];
  212. imageData_1[mipmap] = new Array(faces.length);
  213. var _loop_2 = function (face) {
  214. var specularImageContext = context + "/specularImages/" + mipmap + "/" + face;
  215. this_1._loader.logOpen("" + specularImageContext);
  216. var index = faces[face];
  217. var image = glTF2Loader_1.ArrayItem.Get(specularImageContext, this_1._loader.gltf.images, index);
  218. promises.push(this_1._loader.loadImageAsync("#/images/" + index, image).then(function (data) {
  219. imageData_1[mipmap][face] = data;
  220. }));
  221. this_1._loader.logClose();
  222. };
  223. for (var face = 0; face < faces.length; face++) {
  224. _loop_2(face);
  225. }
  226. };
  227. var this_1 = this;
  228. for (var mipmap = 0; mipmap < light.specularImages.length; mipmap++) {
  229. _loop_1(mipmap);
  230. }
  231. this._loader.logClose();
  232. light._loaded = Promise.all(promises).then(function () {
  233. var babylonTexture = new babylonjs_1.RawCubeTexture(_this._loader.babylonScene, null, light.specularImageSize);
  234. light._babylonTexture = babylonTexture;
  235. if (light.intensity != undefined) {
  236. babylonTexture.level = light.intensity;
  237. }
  238. if (light.rotation) {
  239. var rotation = babylonjs_1.Quaternion.FromArray(light.rotation);
  240. // Invert the rotation so that positive rotation is counter-clockwise.
  241. if (!_this._loader.babylonScene.useRightHandedSystem) {
  242. rotation = babylonjs_1.Quaternion.Inverse(rotation);
  243. }
  244. babylonjs_1.Matrix.FromQuaternionToRef(rotation, babylonTexture.getReflectionTextureMatrix());
  245. }
  246. var sphericalHarmonics = babylonjs_1.SphericalHarmonics.FromArray(light.irradianceCoefficients);
  247. sphericalHarmonics.scale(light.intensity);
  248. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  249. var sphericalPolynomial = babylonjs_1.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  250. // Compute the lod generation scale to fit exactly to the number of levels available.
  251. var lodGenerationScale = (imageData_1.length - 1) / babylonjs_1.Scalar.Log2(light.specularImageSize);
  252. return babylonTexture.updateRGBDAsync(imageData_1, sphericalPolynomial, lodGenerationScale);
  253. });
  254. }
  255. return light._loaded.then(function () {
  256. return light._babylonTexture;
  257. });
  258. };
  259. return EXT_lights_image_based;
  260. }());
  261. exports.EXT_lights_image_based = EXT_lights_image_based;
  262. glTF2Loader_1.GLTF2Loader.RegisterExtension(NAME, function (loader) { return new EXT_lights_image_based(loader); });
  263. /***/ }),
  264. /***/ "./src/glTF/2.0/Extensions/KHR_draco_mesh_compression.ts":
  265. /*!***************************************************************!*\
  266. !*** ./src/glTF/2.0/Extensions/KHR_draco_mesh_compression.ts ***!
  267. \***************************************************************/
  268. /*! no static exports found */
  269. /***/ (function(module, exports, __webpack_require__) {
  270. "use strict";
  271. Object.defineProperty(exports, "__esModule", { value: true });
  272. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  273. var glTF2Loader_1 = __webpack_require__(/*! ../glTF2Loader */ "./src/glTF/2.0/glTF2Loader.ts");
  274. var NAME = "KHR_draco_mesh_compression";
  275. /**
  276. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  277. */
  278. var KHR_draco_mesh_compression = /** @class */ (function () {
  279. /** @hidden */
  280. function KHR_draco_mesh_compression(loader) {
  281. /** The name of this extension. */
  282. this.name = NAME;
  283. /** Defines whether this extension is enabled. */
  284. this.enabled = babylonjs_1.DracoCompression.DecoderAvailable;
  285. this._loader = loader;
  286. }
  287. /** @hidden */
  288. KHR_draco_mesh_compression.prototype.dispose = function () {
  289. if (this._dracoCompression) {
  290. this._dracoCompression.dispose();
  291. delete this._dracoCompression;
  292. }
  293. delete this._loader;
  294. };
  295. /** @hidden */
  296. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  297. var _this = this;
  298. return glTF2Loader_1.GLTF2Loader.LoadExtensionAsync(context, primitive, this.name, function (extensionContext, extension) {
  299. if (primitive.mode != undefined) {
  300. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  301. primitive.mode !== 4 /* TRIANGLES */) {
  302. throw new Error(context + ": Unsupported mode " + primitive.mode);
  303. }
  304. // TODO: handle triangle strips
  305. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  306. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  307. }
  308. }
  309. var attributes = {};
  310. var loadAttribute = function (name, kind) {
  311. var uniqueId = extension.attributes[name];
  312. if (uniqueId == undefined) {
  313. return;
  314. }
  315. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  316. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  317. babylonMesh._delayInfo.push(kind);
  318. }
  319. attributes[kind] = uniqueId;
  320. };
  321. loadAttribute("POSITION", babylonjs_1.VertexBuffer.PositionKind);
  322. loadAttribute("NORMAL", babylonjs_1.VertexBuffer.NormalKind);
  323. loadAttribute("TANGENT", babylonjs_1.VertexBuffer.TangentKind);
  324. loadAttribute("TEXCOORD_0", babylonjs_1.VertexBuffer.UVKind);
  325. loadAttribute("TEXCOORD_1", babylonjs_1.VertexBuffer.UV2Kind);
  326. loadAttribute("JOINTS_0", babylonjs_1.VertexBuffer.MatricesIndicesKind);
  327. loadAttribute("WEIGHTS_0", babylonjs_1.VertexBuffer.MatricesWeightsKind);
  328. loadAttribute("COLOR_0", babylonjs_1.VertexBuffer.ColorKind);
  329. var bufferView = glTF2Loader_1.ArrayItem.Get(extensionContext, _this._loader.gltf.bufferViews, extension.bufferView);
  330. if (!bufferView._dracoBabylonGeometry) {
  331. bufferView._dracoBabylonGeometry = _this._loader.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  332. if (!_this._dracoCompression) {
  333. _this._dracoCompression = new babylonjs_1.DracoCompression();
  334. }
  335. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  336. var babylonGeometry = new babylonjs_1.Geometry(babylonMesh.name, _this._loader.babylonScene);
  337. babylonVertexData.applyToGeometry(babylonGeometry);
  338. return babylonGeometry;
  339. }).catch(function (error) {
  340. throw new Error(context + ": " + error.message);
  341. });
  342. });
  343. }
  344. return bufferView._dracoBabylonGeometry;
  345. });
  346. };
  347. return KHR_draco_mesh_compression;
  348. }());
  349. exports.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  350. glTF2Loader_1.GLTF2Loader.RegisterExtension(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  351. /***/ }),
  352. /***/ "./src/glTF/2.0/Extensions/KHR_lights_punctual.ts":
  353. /*!********************************************************!*\
  354. !*** ./src/glTF/2.0/Extensions/KHR_lights_punctual.ts ***!
  355. \********************************************************/
  356. /*! no static exports found */
  357. /***/ (function(module, exports, __webpack_require__) {
  358. "use strict";
  359. Object.defineProperty(exports, "__esModule", { value: true });
  360. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  361. var glTF2Loader_1 = __webpack_require__(/*! ../glTF2Loader */ "./src/glTF/2.0/glTF2Loader.ts");
  362. var NAME = "KHR_lights_punctual";
  363. var LightType;
  364. (function (LightType) {
  365. LightType["DIRECTIONAL"] = "directional";
  366. LightType["POINT"] = "point";
  367. LightType["SPOT"] = "spot";
  368. })(LightType || (LightType = {}));
  369. /**
  370. * [Specification](https://github.com/KhronosGroup/glTF/blob/1048d162a44dbcb05aefc1874bfd423cf60135a6/extensions/2.0/Khronos/KHR_lights_punctual/README.md) (Experimental)
  371. */
  372. var KHR_lights = /** @class */ (function () {
  373. /** @hidden */
  374. function KHR_lights(loader) {
  375. /** The name of this extension. */
  376. this.name = NAME;
  377. /** Defines whether this extension is enabled. */
  378. this.enabled = true;
  379. this._loader = loader;
  380. }
  381. /** @hidden */
  382. KHR_lights.prototype.dispose = function () {
  383. delete this._loader;
  384. delete this._lights;
  385. };
  386. /** @hidden */
  387. KHR_lights.prototype.onLoading = function () {
  388. var extensions = this._loader.gltf.extensions;
  389. if (extensions && extensions[this.name]) {
  390. var extension = extensions[this.name];
  391. this._lights = extension.lights;
  392. }
  393. };
  394. /** @hidden */
  395. KHR_lights.prototype.loadNodeAsync = function (context, node, assign) {
  396. var _this = this;
  397. return glTF2Loader_1.GLTF2Loader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  398. return _this._loader.loadNodeAsync(context, node, function (babylonMesh) {
  399. var babylonLight;
  400. var light = glTF2Loader_1.ArrayItem.Get(extensionContext, _this._lights, extension.light);
  401. var name = light.name || babylonMesh.name;
  402. switch (light.type) {
  403. case LightType.DIRECTIONAL: {
  404. babylonLight = new babylonjs_1.DirectionalLight(name, babylonjs_1.Vector3.Backward(), _this._loader.babylonScene);
  405. break;
  406. }
  407. case LightType.POINT: {
  408. babylonLight = new babylonjs_1.PointLight(name, babylonjs_1.Vector3.Zero(), _this._loader.babylonScene);
  409. break;
  410. }
  411. case LightType.SPOT: {
  412. var babylonSpotLight = new babylonjs_1.SpotLight(name, babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Backward(), 0, 1, _this._loader.babylonScene);
  413. babylonSpotLight.angle = ((light.spot && light.spot.outerConeAngle) || Math.PI / 4) * 2;
  414. babylonSpotLight.innerAngle = ((light.spot && light.spot.innerConeAngle) || 0) * 2;
  415. babylonLight = babylonSpotLight;
  416. break;
  417. }
  418. default: {
  419. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  420. }
  421. }
  422. babylonLight.falloffType = babylonjs_1.Light.FALLOFF_GLTF;
  423. babylonLight.diffuse = light.color ? babylonjs_1.Color3.FromArray(light.color) : babylonjs_1.Color3.White();
  424. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  425. babylonLight.range = light.range == undefined ? Number.MAX_VALUE : light.range;
  426. babylonLight.parent = babylonMesh;
  427. assign(babylonMesh);
  428. });
  429. });
  430. };
  431. return KHR_lights;
  432. }());
  433. exports.KHR_lights = KHR_lights;
  434. glTF2Loader_1.GLTF2Loader.RegisterExtension(NAME, function (loader) { return new KHR_lights(loader); });
  435. /***/ }),
  436. /***/ "./src/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.ts":
  437. /*!************************************************************************!*\
  438. !*** ./src/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.ts ***!
  439. \************************************************************************/
  440. /*! no static exports found */
  441. /***/ (function(module, exports, __webpack_require__) {
  442. "use strict";
  443. Object.defineProperty(exports, "__esModule", { value: true });
  444. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  445. var glTF2Loader_1 = __webpack_require__(/*! ../glTF2Loader */ "./src/glTF/2.0/glTF2Loader.ts");
  446. var NAME = "KHR_materials_pbrSpecularGlossiness";
  447. /**
  448. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  449. */
  450. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function () {
  451. /** @hidden */
  452. function KHR_materials_pbrSpecularGlossiness(loader) {
  453. /** The name of this extension. */
  454. this.name = NAME;
  455. /** Defines whether this extension is enabled. */
  456. this.enabled = true;
  457. this._loader = loader;
  458. }
  459. /** @hidden */
  460. KHR_materials_pbrSpecularGlossiness.prototype.dispose = function () {
  461. delete this._loader;
  462. };
  463. /** @hidden */
  464. KHR_materials_pbrSpecularGlossiness.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  465. var _this = this;
  466. return glTF2Loader_1.GLTF2Loader.LoadExtensionAsync(context, material, this.name, function (extensionContext, extension) {
  467. var promises = new Array();
  468. promises.push(_this._loader.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  469. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  470. _this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);
  471. return Promise.all(promises).then(function () { });
  472. });
  473. };
  474. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  475. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  476. throw new Error(context + ": Material type not supported");
  477. }
  478. var promises = new Array();
  479. babylonMaterial.metallic = null;
  480. babylonMaterial.roughness = null;
  481. if (properties.diffuseFactor) {
  482. babylonMaterial.albedoColor = babylonjs_1.Color3.FromArray(properties.diffuseFactor);
  483. babylonMaterial.alpha = properties.diffuseFactor[3];
  484. }
  485. else {
  486. babylonMaterial.albedoColor = babylonjs_1.Color3.White();
  487. }
  488. babylonMaterial.reflectivityColor = properties.specularFactor ? babylonjs_1.Color3.FromArray(properties.specularFactor) : babylonjs_1.Color3.White();
  489. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  490. if (properties.diffuseTexture) {
  491. promises.push(this._loader.loadTextureInfoAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  492. babylonMaterial.albedoTexture = texture;
  493. return Promise.resolve();
  494. }));
  495. }
  496. if (properties.specularGlossinessTexture) {
  497. promises.push(this._loader.loadTextureInfoAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  498. babylonMaterial.reflectivityTexture = texture;
  499. return Promise.resolve();
  500. }));
  501. babylonMaterial.reflectivityTexture.hasAlpha = true;
  502. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  503. }
  504. return Promise.all(promises).then(function () { });
  505. };
  506. return KHR_materials_pbrSpecularGlossiness;
  507. }());
  508. exports.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  509. glTF2Loader_1.GLTF2Loader.RegisterExtension(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  510. /***/ }),
  511. /***/ "./src/glTF/2.0/Extensions/KHR_materials_unlit.ts":
  512. /*!********************************************************!*\
  513. !*** ./src/glTF/2.0/Extensions/KHR_materials_unlit.ts ***!
  514. \********************************************************/
  515. /*! no static exports found */
  516. /***/ (function(module, exports, __webpack_require__) {
  517. "use strict";
  518. Object.defineProperty(exports, "__esModule", { value: true });
  519. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  520. var glTF2Loader_1 = __webpack_require__(/*! ../glTF2Loader */ "./src/glTF/2.0/glTF2Loader.ts");
  521. var NAME = "KHR_materials_unlit";
  522. /**
  523. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  524. */
  525. var KHR_materials_unlit = /** @class */ (function () {
  526. /** @hidden */
  527. function KHR_materials_unlit(loader) {
  528. /** The name of this extension. */
  529. this.name = NAME;
  530. /** Defines whether this extension is enabled. */
  531. this.enabled = true;
  532. this._loader = loader;
  533. }
  534. /** @hidden */
  535. KHR_materials_unlit.prototype.dispose = function () {
  536. delete this._loader;
  537. };
  538. /** @hidden */
  539. KHR_materials_unlit.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  540. var _this = this;
  541. return glTF2Loader_1.GLTF2Loader.LoadExtensionAsync(context, material, this.name, function () {
  542. return _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  543. });
  544. };
  545. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  546. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  547. throw new Error(context + ": Material type not supported");
  548. }
  549. var promises = new Array();
  550. babylonMaterial.unlit = true;
  551. var properties = material.pbrMetallicRoughness;
  552. if (properties) {
  553. if (properties.baseColorFactor) {
  554. babylonMaterial.albedoColor = babylonjs_1.Color3.FromArray(properties.baseColorFactor);
  555. babylonMaterial.alpha = properties.baseColorFactor[3];
  556. }
  557. else {
  558. babylonMaterial.albedoColor = babylonjs_1.Color3.White();
  559. }
  560. if (properties.baseColorTexture) {
  561. promises.push(this._loader.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  562. babylonMaterial.albedoTexture = texture;
  563. return Promise.resolve();
  564. }));
  565. }
  566. }
  567. if (material.doubleSided) {
  568. babylonMaterial.backFaceCulling = false;
  569. babylonMaterial.twoSidedLighting = true;
  570. }
  571. this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);
  572. return Promise.all(promises).then(function () { });
  573. };
  574. return KHR_materials_unlit;
  575. }());
  576. exports.KHR_materials_unlit = KHR_materials_unlit;
  577. glTF2Loader_1.GLTF2Loader.RegisterExtension(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  578. /***/ }),
  579. /***/ "./src/glTF/2.0/Extensions/KHR_texture_transform.ts":
  580. /*!**********************************************************!*\
  581. !*** ./src/glTF/2.0/Extensions/KHR_texture_transform.ts ***!
  582. \**********************************************************/
  583. /*! no static exports found */
  584. /***/ (function(module, exports, __webpack_require__) {
  585. "use strict";
  586. Object.defineProperty(exports, "__esModule", { value: true });
  587. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  588. var glTF2Loader_1 = __webpack_require__(/*! ../glTF2Loader */ "./src/glTF/2.0/glTF2Loader.ts");
  589. var NAME = "KHR_texture_transform";
  590. /**
  591. * [Specification](https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_texture_transform/README.md)
  592. */
  593. var KHR_texture_transform = /** @class */ (function () {
  594. /** @hidden */
  595. function KHR_texture_transform(loader) {
  596. /** The name of this extension. */
  597. this.name = NAME;
  598. /** Defines whether this extension is enabled. */
  599. this.enabled = true;
  600. this._loader = loader;
  601. }
  602. /** @hidden */
  603. KHR_texture_transform.prototype.dispose = function () {
  604. delete this._loader;
  605. };
  606. /** @hidden */
  607. KHR_texture_transform.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) {
  608. var _this = this;
  609. return glTF2Loader_1.GLTF2Loader.LoadExtensionAsync(context, textureInfo, this.name, function (extensionContext, extension) {
  610. return _this._loader.loadTextureInfoAsync(context, textureInfo, function (babylonTexture) {
  611. if (!(babylonTexture instanceof babylonjs_1.Texture)) {
  612. throw new Error(extensionContext + ": Texture type not supported");
  613. }
  614. if (extension.offset) {
  615. babylonTexture.uOffset = extension.offset[0];
  616. babylonTexture.vOffset = extension.offset[1];
  617. }
  618. // Always rotate around the origin.
  619. babylonTexture.uRotationCenter = 0;
  620. babylonTexture.vRotationCenter = 0;
  621. if (extension.rotation) {
  622. babylonTexture.wAng = -extension.rotation;
  623. }
  624. if (extension.scale) {
  625. babylonTexture.uScale = extension.scale[0];
  626. babylonTexture.vScale = extension.scale[1];
  627. }
  628. if (extension.texCoord != undefined) {
  629. babylonTexture.coordinatesIndex = extension.texCoord;
  630. }
  631. assign(babylonTexture);
  632. });
  633. });
  634. };
  635. return KHR_texture_transform;
  636. }());
  637. exports.KHR_texture_transform = KHR_texture_transform;
  638. glTF2Loader_1.GLTF2Loader.RegisterExtension(NAME, function (loader) { return new KHR_texture_transform(loader); });
  639. /***/ }),
  640. /***/ "./src/glTF/2.0/Extensions/MSFT_audio_emitter.ts":
  641. /*!*******************************************************!*\
  642. !*** ./src/glTF/2.0/Extensions/MSFT_audio_emitter.ts ***!
  643. \*******************************************************/
  644. /*! no static exports found */
  645. /***/ (function(module, exports, __webpack_require__) {
  646. "use strict";
  647. Object.defineProperty(exports, "__esModule", { value: true });
  648. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  649. var glTF2Loader_1 = __webpack_require__(/*! ../glTF2Loader */ "./src/glTF/2.0/glTF2Loader.ts");
  650. var NAME = "MSFT_audio_emitter";
  651. /**
  652. * [Specification](https://github.com/najadojo/glTF/tree/MSFT_audio_emitter/extensions/2.0/Vendor/MSFT_audio_emitter)
  653. */
  654. var MSFT_audio_emitter = /** @class */ (function () {
  655. /** @hidden */
  656. function MSFT_audio_emitter(loader) {
  657. /** The name of this extension. */
  658. this.name = NAME;
  659. /** Defines whether this extension is enabled. */
  660. this.enabled = true;
  661. this._loader = loader;
  662. }
  663. /** @hidden */
  664. MSFT_audio_emitter.prototype.dispose = function () {
  665. delete this._loader;
  666. delete this._clips;
  667. delete this._emitters;
  668. };
  669. /** @hidden */
  670. MSFT_audio_emitter.prototype.onLoading = function () {
  671. var extensions = this._loader.gltf.extensions;
  672. if (extensions && extensions[this.name]) {
  673. var extension = extensions[this.name];
  674. this._clips = extension.clips;
  675. this._emitters = extension.emitters;
  676. glTF2Loader_1.ArrayItem.Assign(this._clips);
  677. glTF2Loader_1.ArrayItem.Assign(this._emitters);
  678. }
  679. };
  680. /** @hidden */
  681. MSFT_audio_emitter.prototype.loadSceneAsync = function (context, scene) {
  682. var _this = this;
  683. return glTF2Loader_1.GLTF2Loader.LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) {
  684. var promises = new Array();
  685. promises.push(_this._loader.loadSceneAsync(context, scene));
  686. for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) {
  687. var emitterIndex = _a[_i];
  688. var emitter = glTF2Loader_1.ArrayItem.Get(extensionContext + "/emitters", _this._emitters, emitterIndex);
  689. if (emitter.refDistance != undefined || emitter.maxDistance != undefined || emitter.rolloffFactor != undefined ||
  690. emitter.distanceModel != undefined || emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  691. throw new Error(extensionContext + ": Direction or Distance properties are not allowed on emitters attached to a scene");
  692. }
  693. promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter.index, emitter));
  694. }
  695. return Promise.all(promises).then(function () { });
  696. });
  697. };
  698. /** @hidden */
  699. MSFT_audio_emitter.prototype.loadNodeAsync = function (context, node, assign) {
  700. var _this = this;
  701. return glTF2Loader_1.GLTF2Loader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  702. var promises = new Array();
  703. return _this._loader.loadNodeAsync(extensionContext, node, function (babylonMesh) {
  704. var _loop_1 = function (emitterIndex) {
  705. var emitter = glTF2Loader_1.ArrayItem.Get(extensionContext + "/emitters", _this._emitters, emitterIndex);
  706. promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter.index, emitter).then(function () {
  707. for (var _i = 0, _a = emitter._babylonSounds; _i < _a.length; _i++) {
  708. var sound = _a[_i];
  709. sound.attachToMesh(babylonMesh);
  710. if (emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  711. sound.setLocalDirectionToMesh(babylonjs_1.Vector3.Forward());
  712. sound.setDirectionalCone(2 * babylonjs_1.Tools.ToDegrees(emitter.innerAngle == undefined ? Math.PI : emitter.innerAngle), 2 * babylonjs_1.Tools.ToDegrees(emitter.outerAngle == undefined ? Math.PI : emitter.outerAngle), 0);
  713. }
  714. }
  715. }));
  716. };
  717. for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) {
  718. var emitterIndex = _a[_i];
  719. _loop_1(emitterIndex);
  720. }
  721. assign(babylonMesh);
  722. }).then(function (babylonMesh) {
  723. return Promise.all(promises).then(function () {
  724. return babylonMesh;
  725. });
  726. });
  727. });
  728. };
  729. /** @hidden */
  730. MSFT_audio_emitter.prototype.loadAnimationAsync = function (context, animation) {
  731. var _this = this;
  732. return glTF2Loader_1.GLTF2Loader.LoadExtensionAsync(context, animation, this.name, function (extensionContext, extension) {
  733. return _this._loader.loadAnimationAsync(context, animation).then(function (babylonAnimationGroup) {
  734. var promises = new Array();
  735. glTF2Loader_1.ArrayItem.Assign(extension.events);
  736. for (var _i = 0, _a = extension.events; _i < _a.length; _i++) {
  737. var event_1 = _a[_i];
  738. promises.push(_this._loadAnimationEventAsync(extensionContext + "/events/" + event_1.index, context, animation, event_1, babylonAnimationGroup));
  739. }
  740. return Promise.all(promises).then(function () {
  741. return babylonAnimationGroup;
  742. });
  743. });
  744. });
  745. };
  746. MSFT_audio_emitter.prototype._loadClipAsync = function (context, clip) {
  747. if (clip._objectURL) {
  748. return clip._objectURL;
  749. }
  750. var promise;
  751. if (clip.uri) {
  752. promise = this._loader.loadUriAsync(context, clip.uri);
  753. }
  754. else {
  755. var bufferView = glTF2Loader_1.ArrayItem.Get(context + "/bufferView", this._loader.gltf.bufferViews, clip.bufferView);
  756. promise = this._loader.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView);
  757. }
  758. clip._objectURL = promise.then(function (data) {
  759. return URL.createObjectURL(new Blob([data], { type: clip.mimeType }));
  760. });
  761. return clip._objectURL;
  762. };
  763. MSFT_audio_emitter.prototype._loadEmitterAsync = function (context, emitter) {
  764. var _this = this;
  765. emitter._babylonSounds = emitter._babylonSounds || [];
  766. if (!emitter._babylonData) {
  767. var clipPromises = new Array();
  768. var name_1 = emitter.name || "emitter" + emitter.index;
  769. var options_1 = {
  770. loop: false,
  771. autoplay: false,
  772. volume: emitter.volume == undefined ? 1 : emitter.volume,
  773. };
  774. var _loop_2 = function (i) {
  775. var clipContext = "#/extensions/" + this_1.name + "/clips";
  776. var clip = glTF2Loader_1.ArrayItem.Get(clipContext, this_1._clips, emitter.clips[i].clip);
  777. clipPromises.push(this_1._loadClipAsync(clipContext + "/" + emitter.clips[i].clip, clip).then(function (objectURL) {
  778. var sound = emitter._babylonSounds[i] = new babylonjs_1.Sound(name_1, objectURL, _this._loader.babylonScene, null, options_1);
  779. sound.refDistance = emitter.refDistance || 1;
  780. sound.maxDistance = emitter.maxDistance || 256;
  781. sound.rolloffFactor = emitter.rolloffFactor || 1;
  782. sound.distanceModel = emitter.distanceModel || 'exponential';
  783. sound._positionInEmitterSpace = true;
  784. }));
  785. };
  786. var this_1 = this;
  787. for (var i = 0; i < emitter.clips.length; i++) {
  788. _loop_2(i);
  789. }
  790. var promise = Promise.all(clipPromises).then(function () {
  791. var weights = emitter.clips.map(function (clip) { return clip.weight || 1; });
  792. var weightedSound = new babylonjs_1.WeightedSound(emitter.loop || false, emitter._babylonSounds, weights);
  793. if (emitter.innerAngle) {
  794. weightedSound.directionalConeInnerAngle = 2 * babylonjs_1.Tools.ToDegrees(emitter.innerAngle);
  795. }
  796. if (emitter.outerAngle) {
  797. weightedSound.directionalConeOuterAngle = 2 * babylonjs_1.Tools.ToDegrees(emitter.outerAngle);
  798. }
  799. if (emitter.volume) {
  800. weightedSound.volume = emitter.volume;
  801. }
  802. emitter._babylonData.sound = weightedSound;
  803. });
  804. emitter._babylonData = {
  805. loaded: promise
  806. };
  807. }
  808. return emitter._babylonData.loaded;
  809. };
  810. MSFT_audio_emitter.prototype._getEventAction = function (context, sound, action, time, startOffset) {
  811. switch (action) {
  812. case "play" /* play */: {
  813. return function (currentFrame) {
  814. var frameOffset = (startOffset || 0) + (currentFrame - time);
  815. sound.play(frameOffset);
  816. };
  817. }
  818. case "stop" /* stop */: {
  819. return function (currentFrame) {
  820. sound.stop();
  821. };
  822. }
  823. case "pause" /* pause */: {
  824. return function (currentFrame) {
  825. sound.pause();
  826. };
  827. }
  828. default: {
  829. throw new Error(context + ": Unsupported action " + action);
  830. }
  831. }
  832. };
  833. MSFT_audio_emitter.prototype._loadAnimationEventAsync = function (context, animationContext, animation, event, babylonAnimationGroup) {
  834. var _this = this;
  835. if (babylonAnimationGroup.targetedAnimations.length == 0) {
  836. return Promise.resolve();
  837. }
  838. var babylonAnimation = babylonAnimationGroup.targetedAnimations[0];
  839. var emitterIndex = event.emitter;
  840. var emitter = glTF2Loader_1.ArrayItem.Get("#/extensions/" + this.name + "/emitters", this._emitters, emitterIndex);
  841. return this._loadEmitterAsync(context, emitter).then(function () {
  842. var sound = emitter._babylonData.sound;
  843. if (sound) {
  844. var babylonAnimationEvent = new babylonjs_1.AnimationEvent(event.time, _this._getEventAction(context, sound, event.action, event.time, event.startOffset));
  845. babylonAnimation.animation.addEvent(babylonAnimationEvent);
  846. // Make sure all started audio stops when this animation is terminated.
  847. babylonAnimationGroup.onAnimationGroupEndObservable.add(function () {
  848. sound.stop();
  849. });
  850. babylonAnimationGroup.onAnimationGroupPauseObservable.add(function () {
  851. sound.pause();
  852. });
  853. }
  854. });
  855. };
  856. return MSFT_audio_emitter;
  857. }());
  858. exports.MSFT_audio_emitter = MSFT_audio_emitter;
  859. glTF2Loader_1.GLTF2Loader.RegisterExtension(NAME, function (loader) { return new MSFT_audio_emitter(loader); });
  860. /***/ }),
  861. /***/ "./src/glTF/2.0/Extensions/MSFT_lod.ts":
  862. /*!*********************************************!*\
  863. !*** ./src/glTF/2.0/Extensions/MSFT_lod.ts ***!
  864. \*********************************************/
  865. /*! no static exports found */
  866. /***/ (function(module, exports, __webpack_require__) {
  867. "use strict";
  868. Object.defineProperty(exports, "__esModule", { value: true });
  869. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  870. var glTF2Loader_1 = __webpack_require__(/*! ../glTF2Loader */ "./src/glTF/2.0/glTF2Loader.ts");
  871. var NAME = "MSFT_lod";
  872. /**
  873. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  874. */
  875. var MSFT_lod = /** @class */ (function () {
  876. /** @hidden */
  877. function MSFT_lod(loader) {
  878. /** The name of this extension. */
  879. this.name = NAME;
  880. /** Defines whether this extension is enabled. */
  881. this.enabled = true;
  882. /**
  883. * Maximum number of LODs to load, starting from the lowest LOD.
  884. */
  885. this.maxLODsToLoad = Number.MAX_VALUE;
  886. /**
  887. * Observable raised when all node LODs of one level are loaded.
  888. * The event data is the index of the loaded LOD starting from zero.
  889. * Dispose the loader to cancel the loading of the next level of LODs.
  890. */
  891. this.onNodeLODsLoadedObservable = new babylonjs_1.Observable();
  892. /**
  893. * Observable raised when all material LODs of one level are loaded.
  894. * The event data is the index of the loaded LOD starting from zero.
  895. * Dispose the loader to cancel the loading of the next level of LODs.
  896. */
  897. this.onMaterialLODsLoadedObservable = new babylonjs_1.Observable();
  898. this._nodeIndexLOD = null;
  899. this._nodeSignalLODs = new Array();
  900. this._nodePromiseLODs = new Array();
  901. this._materialIndexLOD = null;
  902. this._materialSignalLODs = new Array();
  903. this._materialPromiseLODs = new Array();
  904. this._loader = loader;
  905. }
  906. /** @hidden */
  907. MSFT_lod.prototype.dispose = function () {
  908. delete this._loader;
  909. this._nodeIndexLOD = null;
  910. this._nodeSignalLODs.length = 0;
  911. this._nodePromiseLODs.length = 0;
  912. this._materialIndexLOD = null;
  913. this._materialSignalLODs.length = 0;
  914. this._materialPromiseLODs.length = 0;
  915. this.onMaterialLODsLoadedObservable.clear();
  916. this.onNodeLODsLoadedObservable.clear();
  917. };
  918. /** @hidden */
  919. MSFT_lod.prototype.onReady = function () {
  920. var _this = this;
  921. var _loop_1 = function (indexLOD) {
  922. var promise = Promise.all(this_1._nodePromiseLODs[indexLOD]).then(function () {
  923. if (indexLOD !== 0) {
  924. _this._loader.endPerformanceCounter("Node LOD " + indexLOD);
  925. }
  926. _this._loader.log("Loaded node LOD " + indexLOD);
  927. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  928. if (indexLOD !== _this._nodePromiseLODs.length - 1) {
  929. _this._loader.startPerformanceCounter("Node LOD " + (indexLOD + 1));
  930. if (_this._nodeSignalLODs[indexLOD]) {
  931. _this._nodeSignalLODs[indexLOD].resolve();
  932. }
  933. }
  934. });
  935. this_1._loader._completePromises.push(promise);
  936. };
  937. var this_1 = this;
  938. for (var indexLOD = 0; indexLOD < this._nodePromiseLODs.length; indexLOD++) {
  939. _loop_1(indexLOD);
  940. }
  941. var _loop_2 = function (indexLOD) {
  942. var promise = Promise.all(this_2._materialPromiseLODs[indexLOD]).then(function () {
  943. if (indexLOD !== 0) {
  944. _this._loader.endPerformanceCounter("Material LOD " + indexLOD);
  945. }
  946. _this._loader.log("Loaded material LOD " + indexLOD);
  947. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  948. if (indexLOD !== _this._materialPromiseLODs.length - 1) {
  949. _this._loader.startPerformanceCounter("Material LOD " + (indexLOD + 1));
  950. if (_this._materialSignalLODs[indexLOD]) {
  951. _this._materialSignalLODs[indexLOD].resolve();
  952. }
  953. }
  954. });
  955. this_2._loader._completePromises.push(promise);
  956. };
  957. var this_2 = this;
  958. for (var indexLOD = 0; indexLOD < this._materialPromiseLODs.length; indexLOD++) {
  959. _loop_2(indexLOD);
  960. }
  961. };
  962. /** @hidden */
  963. MSFT_lod.prototype.loadNodeAsync = function (context, node, assign) {
  964. var _this = this;
  965. return glTF2Loader_1.GLTF2Loader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  966. var firstPromise;
  967. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader.gltf.nodes, extension.ids);
  968. _this._loader.logOpen("" + extensionContext);
  969. var _loop_3 = function (indexLOD) {
  970. var nodeLOD = nodeLODs[indexLOD];
  971. if (indexLOD !== 0) {
  972. _this._nodeIndexLOD = indexLOD;
  973. _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new babylonjs_1.Deferred();
  974. }
  975. var promise = _this._loader.loadNodeAsync("#/nodes/" + nodeLOD.index, nodeLOD).then(function (babylonMesh) {
  976. if (indexLOD !== 0) {
  977. // TODO: should not rely on _babylonMesh
  978. var previousNodeLOD = nodeLODs[indexLOD - 1];
  979. if (previousNodeLOD._babylonMesh) {
  980. previousNodeLOD._babylonMesh.dispose();
  981. delete previousNodeLOD._babylonMesh;
  982. _this._disposeUnusedMaterials();
  983. }
  984. }
  985. return babylonMesh;
  986. });
  987. if (indexLOD === 0) {
  988. firstPromise = promise;
  989. }
  990. else {
  991. _this._nodeIndexLOD = null;
  992. }
  993. _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || [];
  994. _this._nodePromiseLODs[indexLOD].push(promise);
  995. };
  996. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  997. _loop_3(indexLOD);
  998. }
  999. _this._loader.logClose();
  1000. return firstPromise;
  1001. });
  1002. };
  1003. /** @hidden */
  1004. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  1005. var _this = this;
  1006. // Don't load material LODs if already loading a node LOD.
  1007. if (this._nodeIndexLOD) {
  1008. return null;
  1009. }
  1010. return glTF2Loader_1.GLTF2Loader.LoadExtensionAsync(context, material, this.name, function (extensionContext, extension) {
  1011. var firstPromise;
  1012. var materialLODs = _this._getLODs(extensionContext, material, _this._loader.gltf.materials, extension.ids);
  1013. _this._loader.logOpen("" + extensionContext);
  1014. var _loop_4 = function (indexLOD) {
  1015. var materialLOD = materialLODs[indexLOD];
  1016. if (indexLOD !== 0) {
  1017. _this._materialIndexLOD = indexLOD;
  1018. }
  1019. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD.index, materialLOD, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  1020. if (indexLOD === 0) {
  1021. assign(babylonMaterial);
  1022. }
  1023. }).then(function (babylonMaterial) {
  1024. if (indexLOD !== 0) {
  1025. assign(babylonMaterial);
  1026. // TODO: should not rely on _babylonData
  1027. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  1028. if (previousBabylonDataLOD[babylonDrawMode]) {
  1029. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  1030. delete previousBabylonDataLOD[babylonDrawMode];
  1031. }
  1032. }
  1033. return babylonMaterial;
  1034. });
  1035. if (indexLOD === 0) {
  1036. firstPromise = promise;
  1037. }
  1038. else {
  1039. _this._materialIndexLOD = null;
  1040. }
  1041. _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || [];
  1042. _this._materialPromiseLODs[indexLOD].push(promise);
  1043. };
  1044. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  1045. _loop_4(indexLOD);
  1046. }
  1047. _this._loader.logClose();
  1048. return firstPromise;
  1049. });
  1050. };
  1051. /** @hidden */
  1052. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  1053. var _this = this;
  1054. // Defer the loading of uris if loading a material or node LOD.
  1055. if (this._materialIndexLOD !== null) {
  1056. this._loader.log("deferred");
  1057. var previousIndexLOD = this._materialIndexLOD - 1;
  1058. this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new babylonjs_1.Deferred();
  1059. return this._materialSignalLODs[previousIndexLOD].promise.then(function () {
  1060. return _this._loader.loadUriAsync(context, uri);
  1061. });
  1062. }
  1063. else if (this._nodeIndexLOD !== null) {
  1064. this._loader.log("deferred");
  1065. var previousIndexLOD = this._nodeIndexLOD - 1;
  1066. this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new babylonjs_1.Deferred();
  1067. return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () {
  1068. return _this._loader.loadUriAsync(context, uri);
  1069. });
  1070. }
  1071. return null;
  1072. };
  1073. /**
  1074. * Gets an array of LOD properties from lowest to highest.
  1075. */
  1076. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  1077. if (this.maxLODsToLoad <= 0) {
  1078. throw new Error("maxLODsToLoad must be greater than zero");
  1079. }
  1080. var properties = new Array();
  1081. for (var i = ids.length - 1; i >= 0; i--) {
  1082. properties.push(glTF2Loader_1.ArrayItem.Get(context + "/ids/" + ids[i], array, ids[i]));
  1083. if (properties.length === this.maxLODsToLoad) {
  1084. return properties;
  1085. }
  1086. }
  1087. properties.push(property);
  1088. return properties;
  1089. };
  1090. MSFT_lod.prototype._disposeUnusedMaterials = function () {
  1091. // TODO: should not rely on _babylonData
  1092. var materials = this._loader.gltf.materials;
  1093. if (materials) {
  1094. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  1095. var material = materials_1[_i];
  1096. if (material._babylonData) {
  1097. for (var drawMode in material._babylonData) {
  1098. var babylonData = material._babylonData[drawMode];
  1099. if (babylonData.meshes.length === 0) {
  1100. babylonData.material.dispose(false, true);
  1101. delete material._babylonData[drawMode];
  1102. }
  1103. }
  1104. }
  1105. }
  1106. }
  1107. };
  1108. return MSFT_lod;
  1109. }());
  1110. exports.MSFT_lod = MSFT_lod;
  1111. glTF2Loader_1.GLTF2Loader.RegisterExtension(NAME, function (loader) { return new MSFT_lod(loader); });
  1112. /***/ }),
  1113. /***/ "./src/glTF/2.0/Extensions/MSFT_minecraftMesh.ts":
  1114. /*!*******************************************************!*\
  1115. !*** ./src/glTF/2.0/Extensions/MSFT_minecraftMesh.ts ***!
  1116. \*******************************************************/
  1117. /*! no static exports found */
  1118. /***/ (function(module, exports, __webpack_require__) {
  1119. "use strict";
  1120. Object.defineProperty(exports, "__esModule", { value: true });
  1121. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  1122. var glTF2Loader_1 = __webpack_require__(/*! ../glTF2Loader */ "./src/glTF/2.0/glTF2Loader.ts");
  1123. var NAME = "MSFT_minecraftMesh";
  1124. /** @hidden */
  1125. var MSFT_minecraftMesh = /** @class */ (function () {
  1126. function MSFT_minecraftMesh(loader) {
  1127. this.name = NAME;
  1128. this.enabled = true;
  1129. this._loader = loader;
  1130. }
  1131. MSFT_minecraftMesh.prototype.dispose = function () {
  1132. delete this._loader;
  1133. };
  1134. MSFT_minecraftMesh.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  1135. var _this = this;
  1136. return glTF2Loader_1.GLTF2Loader.LoadExtraAsync(context, material, this.name, function (extraContext, extra) {
  1137. if (extra) {
  1138. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  1139. throw new Error(extraContext + ": Material type not supported");
  1140. }
  1141. var promise = _this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);
  1142. if (babylonMaterial.needAlphaBlending()) {
  1143. babylonMaterial.forceDepthWrite = true;
  1144. babylonMaterial.separateCullingPass = true;
  1145. }
  1146. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  1147. babylonMaterial.twoSidedLighting = true;
  1148. return promise;
  1149. }
  1150. return null;
  1151. });
  1152. };
  1153. return MSFT_minecraftMesh;
  1154. }());
  1155. exports.MSFT_minecraftMesh = MSFT_minecraftMesh;
  1156. glTF2Loader_1.GLTF2Loader.RegisterExtension(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  1157. /***/ }),
  1158. /***/ "./src/glTF/2.0/Extensions/MSFT_sRGBFactors.ts":
  1159. /*!*****************************************************!*\
  1160. !*** ./src/glTF/2.0/Extensions/MSFT_sRGBFactors.ts ***!
  1161. \*****************************************************/
  1162. /*! no static exports found */
  1163. /***/ (function(module, exports, __webpack_require__) {
  1164. "use strict";
  1165. Object.defineProperty(exports, "__esModule", { value: true });
  1166. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  1167. var glTF2Loader_1 = __webpack_require__(/*! ../glTF2Loader */ "./src/glTF/2.0/glTF2Loader.ts");
  1168. var NAME = "MSFT_sRGBFactors";
  1169. /** @hidden */
  1170. var MSFT_sRGBFactors = /** @class */ (function () {
  1171. function MSFT_sRGBFactors(loader) {
  1172. this.name = NAME;
  1173. this.enabled = true;
  1174. this._loader = loader;
  1175. }
  1176. MSFT_sRGBFactors.prototype.dispose = function () {
  1177. delete this._loader;
  1178. };
  1179. MSFT_sRGBFactors.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  1180. var _this = this;
  1181. return glTF2Loader_1.GLTF2Loader.LoadExtraAsync(context, material, this.name, function (extraContext, extra) {
  1182. if (extra) {
  1183. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  1184. throw new Error(extraContext + ": Material type not supported");
  1185. }
  1186. var promise = _this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);
  1187. if (!babylonMaterial.albedoTexture) {
  1188. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  1189. }
  1190. if (!babylonMaterial.reflectivityTexture) {
  1191. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  1192. }
  1193. return promise;
  1194. }
  1195. return null;
  1196. });
  1197. };
  1198. return MSFT_sRGBFactors;
  1199. }());
  1200. exports.MSFT_sRGBFactors = MSFT_sRGBFactors;
  1201. glTF2Loader_1.GLTF2Loader.RegisterExtension(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  1202. /***/ }),
  1203. /***/ "./src/glTF/2.0/Extensions/index.ts":
  1204. /*!******************************************!*\
  1205. !*** ./src/glTF/2.0/Extensions/index.ts ***!
  1206. \******************************************/
  1207. /*! no static exports found */
  1208. /***/ (function(module, exports, __webpack_require__) {
  1209. "use strict";
  1210. function __export(m) {
  1211. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  1212. }
  1213. Object.defineProperty(exports, "__esModule", { value: true });
  1214. __export(__webpack_require__(/*! ./EXT_lights_image_based */ "./src/glTF/2.0/Extensions/EXT_lights_image_based.ts"));
  1215. __export(__webpack_require__(/*! ./KHR_draco_mesh_compression */ "./src/glTF/2.0/Extensions/KHR_draco_mesh_compression.ts"));
  1216. __export(__webpack_require__(/*! ./KHR_lights_punctual */ "./src/glTF/2.0/Extensions/KHR_lights_punctual.ts"));
  1217. __export(__webpack_require__(/*! ./KHR_materials_pbrSpecularGlossiness */ "./src/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.ts"));
  1218. __export(__webpack_require__(/*! ./KHR_materials_unlit */ "./src/glTF/2.0/Extensions/KHR_materials_unlit.ts"));
  1219. __export(__webpack_require__(/*! ./KHR_texture_transform */ "./src/glTF/2.0/Extensions/KHR_texture_transform.ts"));
  1220. __export(__webpack_require__(/*! ./MSFT_audio_emitter */ "./src/glTF/2.0/Extensions/MSFT_audio_emitter.ts"));
  1221. __export(__webpack_require__(/*! ./MSFT_lod */ "./src/glTF/2.0/Extensions/MSFT_lod.ts"));
  1222. __export(__webpack_require__(/*! ./MSFT_minecraftMesh */ "./src/glTF/2.0/Extensions/MSFT_minecraftMesh.ts"));
  1223. __export(__webpack_require__(/*! ./MSFT_sRGBFactors */ "./src/glTF/2.0/Extensions/MSFT_sRGBFactors.ts"));
  1224. /***/ }),
  1225. /***/ "./src/glTF/2.0/glTF2Loader.ts":
  1226. /*!*************************************!*\
  1227. !*** ./src/glTF/2.0/glTF2Loader.ts ***!
  1228. \*************************************/
  1229. /*! no static exports found */
  1230. /***/ (function(module, exports, __webpack_require__) {
  1231. "use strict";
  1232. Object.defineProperty(exports, "__esModule", { value: true });
  1233. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  1234. var glTFFileLoader_1 = __webpack_require__(/*! ../glTFFileLoader */ "./src/glTF/glTFFileLoader.ts");
  1235. /**
  1236. * Helper class for working with arrays when loading the glTF asset
  1237. */
  1238. var ArrayItem = /** @class */ (function () {
  1239. function ArrayItem() {
  1240. }
  1241. /**
  1242. * Gets an item from the given array.
  1243. * @param context The context when loading the asset
  1244. * @param array The array to get the item from
  1245. * @param index The index to the array
  1246. * @returns The array item
  1247. */
  1248. ArrayItem.Get = function (context, array, index) {
  1249. if (!array || index == undefined || !array[index]) {
  1250. throw new Error(context + ": Failed to find index (" + index + ")");
  1251. }
  1252. return array[index];
  1253. };
  1254. /**
  1255. * Assign an `index` field to each item of the given array.
  1256. * @param array The array of items
  1257. */
  1258. ArrayItem.Assign = function (array) {
  1259. if (array) {
  1260. for (var index = 0; index < array.length; index++) {
  1261. array[index].index = index;
  1262. }
  1263. }
  1264. };
  1265. return ArrayItem;
  1266. }());
  1267. exports.ArrayItem = ArrayItem;
  1268. /**
  1269. * The glTF 2.0 loader
  1270. */
  1271. var GLTF2Loader = /** @class */ (function () {
  1272. /** @hidden */
  1273. function GLTF2Loader(parent) {
  1274. /** @hidden */
  1275. this._completePromises = new Array();
  1276. this._disposed = false;
  1277. this._state = null;
  1278. this._extensions = {};
  1279. this._defaultBabylonMaterialData = {};
  1280. this._requests = new Array();
  1281. this._parent = parent;
  1282. }
  1283. /**
  1284. * Registers a loader extension.
  1285. * @param name The name of the loader extension.
  1286. * @param factory The factory function that creates the loader extension.
  1287. */
  1288. GLTF2Loader.RegisterExtension = function (name, factory) {
  1289. if (GLTF2Loader.UnregisterExtension(name)) {
  1290. babylonjs_1.Tools.Warn("Extension with the name '" + name + "' already exists");
  1291. }
  1292. GLTF2Loader._ExtensionFactories[name] = factory;
  1293. // Keep the order of registration so that extensions registered first are called first.
  1294. GLTF2Loader._ExtensionNames.push(name);
  1295. };
  1296. /**
  1297. * Unregisters a loader extension.
  1298. * @param name The name of the loader extenion.
  1299. * @returns A boolean indicating whether the extension has been unregistered
  1300. */
  1301. GLTF2Loader.UnregisterExtension = function (name) {
  1302. if (!GLTF2Loader._ExtensionFactories[name]) {
  1303. return false;
  1304. }
  1305. delete GLTF2Loader._ExtensionFactories[name];
  1306. var index = GLTF2Loader._ExtensionNames.indexOf(name);
  1307. if (index !== -1) {
  1308. GLTF2Loader._ExtensionNames.splice(index, 1);
  1309. }
  1310. return true;
  1311. };
  1312. Object.defineProperty(GLTF2Loader.prototype, "state", {
  1313. /**
  1314. * Gets the loader state.
  1315. */
  1316. get: function () {
  1317. return this._state;
  1318. },
  1319. enumerable: true,
  1320. configurable: true
  1321. });
  1322. /** @hidden */
  1323. GLTF2Loader.prototype.dispose = function () {
  1324. if (this._disposed) {
  1325. return;
  1326. }
  1327. this._disposed = true;
  1328. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  1329. var request = _a[_i];
  1330. request.abort();
  1331. }
  1332. this._requests.length = 0;
  1333. delete this.gltf;
  1334. delete this.babylonScene;
  1335. this._completePromises.length = 0;
  1336. for (var name_1 in this._extensions) {
  1337. var extension = this._extensions[name_1];
  1338. if (extension.dispose) {
  1339. this._extensions[name_1].dispose();
  1340. }
  1341. }
  1342. this._extensions = {};
  1343. delete this._rootBabylonMesh;
  1344. delete this._progressCallback;
  1345. this._parent._clear();
  1346. };
  1347. /** @hidden */
  1348. GLTF2Loader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  1349. var _this = this;
  1350. return Promise.resolve().then(function () {
  1351. _this.babylonScene = scene;
  1352. _this._rootUrl = rootUrl;
  1353. _this._fileName = fileName || "scene";
  1354. _this._progressCallback = onProgress;
  1355. _this._loadData(data);
  1356. var nodes = null;
  1357. if (meshesNames) {
  1358. var nodeMap_1 = {};
  1359. if (_this.gltf.nodes) {
  1360. for (var _i = 0, _a = _this.gltf.nodes; _i < _a.length; _i++) {
  1361. var node = _a[_i];
  1362. if (node.name) {
  1363. nodeMap_1[node.name] = node.index;
  1364. }
  1365. }
  1366. }
  1367. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  1368. nodes = names.map(function (name) {
  1369. var node = nodeMap_1[name];
  1370. if (node === undefined) {
  1371. throw new Error("Failed to find node '" + name + "'");
  1372. }
  1373. return node;
  1374. });
  1375. }
  1376. return _this._loadAsync(nodes, function () {
  1377. return {
  1378. meshes: _this._getMeshes(),
  1379. particleSystems: [],
  1380. skeletons: _this._getSkeletons(),
  1381. animationGroups: _this._getAnimationGroups()
  1382. };
  1383. });
  1384. });
  1385. };
  1386. /** @hidden */
  1387. GLTF2Loader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  1388. var _this = this;
  1389. return Promise.resolve().then(function () {
  1390. _this.babylonScene = scene;
  1391. _this._rootUrl = rootUrl;
  1392. _this._fileName = fileName || "scene";
  1393. _this._progressCallback = onProgress;
  1394. _this._loadData(data);
  1395. return _this._loadAsync(null, function () { return undefined; });
  1396. });
  1397. };
  1398. GLTF2Loader.prototype._loadAsync = function (nodes, resultFunc) {
  1399. var _this = this;
  1400. return Promise.resolve().then(function () {
  1401. _this._uniqueRootUrl = (_this._rootUrl.indexOf("file:") === -1 && _this._fileName) ? _this._rootUrl : "" + _this._rootUrl + Date.now() + "/";
  1402. _this._loadExtensions();
  1403. _this._checkExtensions();
  1404. var loadingToReadyCounterName = glTFFileLoader_1.GLTFLoaderState[glTFFileLoader_1.GLTFLoaderState.LOADING] + " => " + glTFFileLoader_1.GLTFLoaderState[glTFFileLoader_1.GLTFLoaderState.READY];
  1405. var loadingToCompleteCounterName = glTFFileLoader_1.GLTFLoaderState[glTFFileLoader_1.GLTFLoaderState.LOADING] + " => " + glTFFileLoader_1.GLTFLoaderState[glTFFileLoader_1.GLTFLoaderState.COMPLETE];
  1406. _this._parent._startPerformanceCounter(loadingToReadyCounterName);
  1407. _this._parent._startPerformanceCounter(loadingToCompleteCounterName);
  1408. _this._setState(glTFFileLoader_1.GLTFLoaderState.LOADING);
  1409. _this._extensionsOnLoading();
  1410. var promises = new Array();
  1411. if (nodes) {
  1412. promises.push(_this.loadSceneAsync("#/nodes", { nodes: nodes, index: -1 }));
  1413. }
  1414. else {
  1415. var scene = ArrayItem.Get("#/scene", _this.gltf.scenes, _this.gltf.scene || 0);
  1416. promises.push(_this.loadSceneAsync("#/scenes/" + scene.index, scene));
  1417. }
  1418. if (_this._parent.compileMaterials) {
  1419. promises.push(_this._compileMaterialsAsync());
  1420. }
  1421. if (_this._parent.compileShadowGenerators) {
  1422. promises.push(_this._compileShadowGeneratorsAsync());
  1423. }
  1424. var resultPromise = Promise.all(promises).then(function () {
  1425. _this._setState(glTFFileLoader_1.GLTFLoaderState.READY);
  1426. _this._extensionsOnReady();
  1427. _this._startAnimations();
  1428. return resultFunc();
  1429. });
  1430. resultPromise.then(function () {
  1431. _this._parent._endPerformanceCounter(loadingToReadyCounterName);
  1432. babylonjs_1.Tools.SetImmediate(function () {
  1433. if (!_this._disposed) {
  1434. Promise.all(_this._completePromises).then(function () {
  1435. _this._parent._endPerformanceCounter(loadingToCompleteCounterName);
  1436. _this._setState(glTFFileLoader_1.GLTFLoaderState.COMPLETE);
  1437. _this._parent.onCompleteObservable.notifyObservers(undefined);
  1438. _this._parent.onCompleteObservable.clear();
  1439. _this.dispose();
  1440. }, function (error) {
  1441. _this._parent.onErrorObservable.notifyObservers(error);
  1442. _this._parent.onErrorObservable.clear();
  1443. _this.dispose();
  1444. });
  1445. }
  1446. });
  1447. });
  1448. return resultPromise;
  1449. }, function (error) {
  1450. if (!_this._disposed) {
  1451. _this._parent.onErrorObservable.notifyObservers(error);
  1452. _this._parent.onErrorObservable.clear();
  1453. _this.dispose();
  1454. }
  1455. throw error;
  1456. });
  1457. };
  1458. GLTF2Loader.prototype._loadData = function (data) {
  1459. this.gltf = data.json;
  1460. this._setupData();
  1461. if (data.bin) {
  1462. var buffers = this.gltf.buffers;
  1463. if (buffers && buffers[0] && !buffers[0].uri) {
  1464. var binaryBuffer = buffers[0];
  1465. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  1466. babylonjs_1.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  1467. }
  1468. binaryBuffer._data = Promise.resolve(data.bin);
  1469. }
  1470. else {
  1471. babylonjs_1.Tools.Warn("Unexpected BIN chunk");
  1472. }
  1473. }
  1474. };
  1475. GLTF2Loader.prototype._setupData = function () {
  1476. ArrayItem.Assign(this.gltf.accessors);
  1477. ArrayItem.Assign(this.gltf.animations);
  1478. ArrayItem.Assign(this.gltf.buffers);
  1479. ArrayItem.Assign(this.gltf.bufferViews);
  1480. ArrayItem.Assign(this.gltf.cameras);
  1481. ArrayItem.Assign(this.gltf.images);
  1482. ArrayItem.Assign(this.gltf.materials);
  1483. ArrayItem.Assign(this.gltf.meshes);
  1484. ArrayItem.Assign(this.gltf.nodes);
  1485. ArrayItem.Assign(this.gltf.samplers);
  1486. ArrayItem.Assign(this.gltf.scenes);
  1487. ArrayItem.Assign(this.gltf.skins);
  1488. ArrayItem.Assign(this.gltf.textures);
  1489. if (this.gltf.nodes) {
  1490. var nodeParents = {};
  1491. for (var _i = 0, _a = this.gltf.nodes; _i < _a.length; _i++) {
  1492. var node = _a[_i];
  1493. if (node.children) {
  1494. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  1495. var index = _c[_b];
  1496. nodeParents[index] = node.index;
  1497. }
  1498. }
  1499. }
  1500. var rootNode = this._createRootNode();
  1501. for (var _d = 0, _e = this.gltf.nodes; _d < _e.length; _d++) {
  1502. var node = _e[_d];
  1503. var parentIndex = nodeParents[node.index];
  1504. node.parent = parentIndex === undefined ? rootNode : this.gltf.nodes[parentIndex];
  1505. }
  1506. }
  1507. };
  1508. GLTF2Loader.prototype._loadExtensions = function () {
  1509. for (var _i = 0, _a = GLTF2Loader._ExtensionNames; _i < _a.length; _i++) {
  1510. var name_2 = _a[_i];
  1511. var extension = GLTF2Loader._ExtensionFactories[name_2](this);
  1512. this._extensions[name_2] = extension;
  1513. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  1514. }
  1515. this._parent.onExtensionLoadedObservable.clear();
  1516. };
  1517. GLTF2Loader.prototype._checkExtensions = function () {
  1518. if (this.gltf.extensionsRequired) {
  1519. for (var _i = 0, _a = this.gltf.extensionsRequired; _i < _a.length; _i++) {
  1520. var name_3 = _a[_i];
  1521. var extension = this._extensions[name_3];
  1522. if (!extension || !extension.enabled) {
  1523. throw new Error("Require extension " + name_3 + " is not available");
  1524. }
  1525. }
  1526. }
  1527. };
  1528. GLTF2Loader.prototype._setState = function (state) {
  1529. this._state = state;
  1530. this.log(glTFFileLoader_1.GLTFLoaderState[this._state]);
  1531. };
  1532. GLTF2Loader.prototype._createRootNode = function () {
  1533. this._rootBabylonMesh = new babylonjs_1.Mesh("__root__", this.babylonScene);
  1534. var rootNode = {
  1535. _babylonMesh: this._rootBabylonMesh,
  1536. index: -1
  1537. };
  1538. switch (this._parent.coordinateSystemMode) {
  1539. case glTFFileLoader_1.GLTFLoaderCoordinateSystemMode.AUTO: {
  1540. if (!this.babylonScene.useRightHandedSystem) {
  1541. rootNode.rotation = [0, 1, 0, 0];
  1542. rootNode.scale = [1, 1, -1];
  1543. GLTF2Loader._LoadTransform(rootNode, this._rootBabylonMesh);
  1544. }
  1545. break;
  1546. }
  1547. case glTFFileLoader_1.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  1548. this.babylonScene.useRightHandedSystem = true;
  1549. break;
  1550. }
  1551. default: {
  1552. throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  1553. }
  1554. }
  1555. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  1556. return rootNode;
  1557. };
  1558. /**
  1559. * Loads a glTF scene.
  1560. * @param context The context when loading the asset
  1561. * @param scene The glTF scene property
  1562. * @returns A promise that resolves when the load is complete
  1563. */
  1564. GLTF2Loader.prototype.loadSceneAsync = function (context, scene) {
  1565. var _this = this;
  1566. var extensionPromise = this._extensionsLoadSceneAsync(context, scene);
  1567. if (extensionPromise) {
  1568. return extensionPromise;
  1569. }
  1570. var promises = new Array();
  1571. this.logOpen(context + " " + (scene.name || ""));
  1572. if (scene.nodes) {
  1573. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  1574. var index = _a[_i];
  1575. var node = ArrayItem.Get(context + "/nodes/" + index, this.gltf.nodes, index);
  1576. promises.push(this.loadNodeAsync("#/nodes/" + node.index, node, function (babylonMesh) {
  1577. babylonMesh.parent = _this._rootBabylonMesh;
  1578. }));
  1579. }
  1580. }
  1581. promises.push(this._loadAnimationsAsync());
  1582. this.logClose();
  1583. return Promise.all(promises).then(function () { });
  1584. };
  1585. GLTF2Loader.prototype._forEachPrimitive = function (node, callback) {
  1586. if (node._primitiveBabylonMeshes) {
  1587. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  1588. var babylonMesh = _a[_i];
  1589. callback(babylonMesh);
  1590. }
  1591. }
  1592. else {
  1593. callback(node._babylonMesh);
  1594. }
  1595. };
  1596. GLTF2Loader.prototype._getMeshes = function () {
  1597. var meshes = new Array();
  1598. // Root mesh is always first.
  1599. meshes.push(this._rootBabylonMesh);
  1600. var nodes = this.gltf.nodes;
  1601. if (nodes) {
  1602. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  1603. var node = nodes_1[_i];
  1604. if (node._babylonMesh) {
  1605. meshes.push(node._babylonMesh);
  1606. }
  1607. if (node._primitiveBabylonMeshes) {
  1608. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  1609. var babylonMesh = _b[_a];
  1610. meshes.push(babylonMesh);
  1611. }
  1612. }
  1613. }
  1614. }
  1615. return meshes;
  1616. };
  1617. GLTF2Loader.prototype._getSkeletons = function () {
  1618. var skeletons = new Array();
  1619. var skins = this.gltf.skins;
  1620. if (skins) {
  1621. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  1622. var skin = skins_1[_i];
  1623. if (skin._babylonSkeleton) {
  1624. skeletons.push(skin._babylonSkeleton);
  1625. }
  1626. }
  1627. }
  1628. return skeletons;
  1629. };
  1630. GLTF2Loader.prototype._getAnimationGroups = function () {
  1631. var animationGroups = new Array();
  1632. var animations = this.gltf.animations;
  1633. if (animations) {
  1634. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  1635. var animation = animations_1[_i];
  1636. if (animation._babylonAnimationGroup) {
  1637. animationGroups.push(animation._babylonAnimationGroup);
  1638. }
  1639. }
  1640. }
  1641. return animationGroups;
  1642. };
  1643. GLTF2Loader.prototype._startAnimations = function () {
  1644. switch (this._parent.animationStartMode) {
  1645. case glTFFileLoader_1.GLTFLoaderAnimationStartMode.NONE: {
  1646. // do nothing
  1647. break;
  1648. }
  1649. case glTFFileLoader_1.GLTFLoaderAnimationStartMode.FIRST: {
  1650. var babylonAnimationGroups = this._getAnimationGroups();
  1651. if (babylonAnimationGroups.length !== 0) {
  1652. babylonAnimationGroups[0].start(true);
  1653. }
  1654. break;
  1655. }
  1656. case glTFFileLoader_1.GLTFLoaderAnimationStartMode.ALL: {
  1657. var babylonAnimationGroups = this._getAnimationGroups();
  1658. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  1659. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  1660. babylonAnimationGroup.start(true);
  1661. }
  1662. break;
  1663. }
  1664. default: {
  1665. babylonjs_1.Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
  1666. return;
  1667. }
  1668. }
  1669. };
  1670. /**
  1671. * Loads a glTF node.
  1672. * @param context The context when loading the asset
  1673. * @param node The glTF node property
  1674. * @param assign A function called synchronously after parsing the glTF properties
  1675. * @returns A promise that resolves with the loaded Babylon mesh when the load is complete
  1676. */
  1677. GLTF2Loader.prototype.loadNodeAsync = function (context, node, assign) {
  1678. var _this = this;
  1679. if (assign === void 0) { assign = function () { }; }
  1680. var extensionPromise = this._extensionsLoadNodeAsync(context, node, assign);
  1681. if (extensionPromise) {
  1682. return extensionPromise;
  1683. }
  1684. if (node._babylonMesh) {
  1685. throw new Error(context + ": Invalid recursive node hierarchy");
  1686. }
  1687. var promises = new Array();
  1688. this.logOpen(context + " " + (node.name || ""));
  1689. var babylonMesh = new babylonjs_1.Mesh(node.name || "node" + node.index, this.babylonScene);
  1690. node._babylonMesh = babylonMesh;
  1691. babylonMesh.setEnabled(false);
  1692. GLTF2Loader._LoadTransform(node, babylonMesh);
  1693. if (node.mesh != undefined) {
  1694. var mesh = ArrayItem.Get(context + "/mesh", this.gltf.meshes, node.mesh);
  1695. promises.push(this._loadMeshAsync("#/meshes/" + mesh.index, node, mesh, babylonMesh));
  1696. }
  1697. if (node.camera != undefined) {
  1698. var camera = ArrayItem.Get(context + "/camera", this.gltf.cameras, node.camera);
  1699. promises.push(this.loadCameraAsync("#/cameras/" + camera.index, camera, function (babylonCamera) {
  1700. babylonCamera.parent = babylonMesh;
  1701. }));
  1702. }
  1703. if (node.children) {
  1704. var _loop_1 = function (index) {
  1705. var childNode = ArrayItem.Get(context + "/children/" + index, this_1.gltf.nodes, index);
  1706. promises.push(this_1.loadNodeAsync("#/nodes/" + node.index, childNode, function (childBabylonMesh) {
  1707. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  1708. if (childNode.skin != undefined) {
  1709. childBabylonMesh.parent = _this._rootBabylonMesh;
  1710. return;
  1711. }
  1712. childBabylonMesh.parent = babylonMesh;
  1713. }));
  1714. };
  1715. var this_1 = this;
  1716. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  1717. var index = _a[_i];
  1718. _loop_1(index);
  1719. }
  1720. }
  1721. assign(babylonMesh);
  1722. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  1723. this.logClose();
  1724. return Promise.all(promises).then(function () {
  1725. babylonMesh.setEnabled(true);
  1726. return babylonMesh;
  1727. });
  1728. };
  1729. GLTF2Loader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  1730. var _this = this;
  1731. var promises = new Array();
  1732. this.logOpen(context + " " + (mesh.name || ""));
  1733. var primitives = mesh.primitives;
  1734. if (!primitives || primitives.length === 0) {
  1735. throw new Error(context + ": Primitives are missing");
  1736. }
  1737. ArrayItem.Assign(primitives);
  1738. if (primitives.length === 1) {
  1739. var primitive = primitives[0];
  1740. promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, node, mesh, primitive, babylonMesh));
  1741. }
  1742. else {
  1743. node._primitiveBabylonMeshes = [];
  1744. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  1745. var primitive = primitives_1[_i];
  1746. var primitiveBabylonMesh = new babylonjs_1.Mesh((mesh.name || babylonMesh.name) + "_" + primitive.index, this.babylonScene, babylonMesh);
  1747. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  1748. promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, node, mesh, primitive, primitiveBabylonMesh));
  1749. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  1750. }
  1751. }
  1752. if (node.skin != undefined) {
  1753. var skin = ArrayItem.Get(context + "/skin", this.gltf.skins, node.skin);
  1754. promises.push(this._loadSkinAsync("#/skins/" + skin.index, node, skin));
  1755. }
  1756. this.logClose();
  1757. return Promise.all(promises).then(function () {
  1758. _this._forEachPrimitive(node, function (babylonMesh) {
  1759. babylonMesh._refreshBoundingInfo(true);
  1760. });
  1761. });
  1762. };
  1763. GLTF2Loader.prototype._loadMeshPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  1764. var _this = this;
  1765. var promises = new Array();
  1766. this.logOpen("" + context);
  1767. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  1768. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  1769. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  1770. babylonGeometry.applyToMesh(babylonMesh);
  1771. });
  1772. }));
  1773. var babylonDrawMode = GLTF2Loader._GetDrawMode(context, primitive.mode);
  1774. if (primitive.material == undefined) {
  1775. var babylonMaterial = this._defaultBabylonMaterialData[babylonDrawMode];
  1776. if (!babylonMaterial) {
  1777. babylonMaterial = this._createDefaultMaterial("__gltf_default", babylonDrawMode);
  1778. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  1779. this._defaultBabylonMaterialData[babylonDrawMode] = babylonMaterial;
  1780. }
  1781. babylonMesh.material = babylonMaterial;
  1782. }
  1783. else {
  1784. var material = ArrayItem.Get(context + "/material", this.gltf.materials, primitive.material);
  1785. promises.push(this._loadMaterialAsync("#/materials/" + material.index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  1786. babylonMesh.material = babylonMaterial;
  1787. }));
  1788. }
  1789. this.logClose();
  1790. return Promise.all(promises).then(function () { });
  1791. };
  1792. GLTF2Loader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  1793. var _this = this;
  1794. var extensionPromise = this._extensionsLoadVertexDataAsync(context, primitive, babylonMesh);
  1795. if (extensionPromise) {
  1796. return extensionPromise;
  1797. }
  1798. var attributes = primitive.attributes;
  1799. if (!attributes) {
  1800. throw new Error(context + ": Attributes are missing");
  1801. }
  1802. var promises = new Array();
  1803. var babylonGeometry = new babylonjs_1.Geometry(babylonMesh.name, this.babylonScene);
  1804. if (primitive.indices == undefined) {
  1805. babylonMesh.isUnIndexed = true;
  1806. }
  1807. else {
  1808. var accessor = ArrayItem.Get(context + "/indices", this.gltf.accessors, primitive.indices);
  1809. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  1810. babylonGeometry.setIndices(data);
  1811. }));
  1812. }
  1813. var loadAttribute = function (attribute, kind, callback) {
  1814. if (attributes[attribute] == undefined) {
  1815. return;
  1816. }
  1817. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  1818. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  1819. babylonMesh._delayInfo.push(kind);
  1820. }
  1821. var accessor = ArrayItem.Get(context + "/attributes/" + attribute, _this.gltf.accessors, attributes[attribute]);
  1822. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor.index, accessor, kind).then(function (babylonVertexBuffer) {
  1823. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  1824. }));
  1825. if (callback) {
  1826. callback(accessor);
  1827. }
  1828. };
  1829. loadAttribute("POSITION", babylonjs_1.VertexBuffer.PositionKind);
  1830. loadAttribute("NORMAL", babylonjs_1.VertexBuffer.NormalKind);
  1831. loadAttribute("TANGENT", babylonjs_1.VertexBuffer.TangentKind);
  1832. loadAttribute("TEXCOORD_0", babylonjs_1.VertexBuffer.UVKind);
  1833. loadAttribute("TEXCOORD_1", babylonjs_1.VertexBuffer.UV2Kind);
  1834. loadAttribute("JOINTS_0", babylonjs_1.VertexBuffer.MatricesIndicesKind);
  1835. loadAttribute("WEIGHTS_0", babylonjs_1.VertexBuffer.MatricesWeightsKind);
  1836. loadAttribute("COLOR_0", babylonjs_1.VertexBuffer.ColorKind, function (accessor) {
  1837. if (accessor.type === "VEC4" /* VEC4 */) {
  1838. babylonMesh.hasVertexAlpha = true;
  1839. }
  1840. });
  1841. return Promise.all(promises).then(function () {
  1842. return babylonGeometry;
  1843. });
  1844. };
  1845. GLTF2Loader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  1846. if (!primitive.targets) {
  1847. return;
  1848. }
  1849. if (node._numMorphTargets == undefined) {
  1850. node._numMorphTargets = primitive.targets.length;
  1851. }
  1852. else if (primitive.targets.length !== node._numMorphTargets) {
  1853. throw new Error(context + ": Primitives do not have the same number of targets");
  1854. }
  1855. babylonMesh.morphTargetManager = new babylonjs_1.MorphTargetManager();
  1856. for (var index = 0; index < primitive.targets.length; index++) {
  1857. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  1858. babylonMesh.morphTargetManager.addTarget(new babylonjs_1.MorphTarget("morphTarget" + index, weight));
  1859. // TODO: tell the target whether it has positions, normals, tangents
  1860. }
  1861. };
  1862. GLTF2Loader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  1863. if (!primitive.targets) {
  1864. return Promise.resolve();
  1865. }
  1866. var promises = new Array();
  1867. var morphTargetManager = babylonMesh.morphTargetManager;
  1868. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  1869. var babylonMorphTarget = morphTargetManager.getTarget(index);
  1870. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  1871. }
  1872. return Promise.all(promises).then(function () { });
  1873. };
  1874. GLTF2Loader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  1875. var _this = this;
  1876. var promises = new Array();
  1877. var loadAttribute = function (attribute, kind, setData) {
  1878. if (attributes[attribute] == undefined) {
  1879. return;
  1880. }
  1881. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  1882. if (!babylonVertexBuffer) {
  1883. return;
  1884. }
  1885. var accessor = ArrayItem.Get(context + "/" + attribute, _this.gltf.accessors, attributes[attribute]);
  1886. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  1887. setData(babylonVertexBuffer, data);
  1888. }));
  1889. };
  1890. loadAttribute("POSITION", babylonjs_1.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  1891. babylonVertexBuffer.forEach(data.length, function (value, index) {
  1892. data[index] += value;
  1893. });
  1894. babylonMorphTarget.setPositions(data);
  1895. });
  1896. loadAttribute("NORMAL", babylonjs_1.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  1897. babylonVertexBuffer.forEach(data.length, function (value, index) {
  1898. data[index] += value;
  1899. });
  1900. babylonMorphTarget.setNormals(data);
  1901. });
  1902. loadAttribute("TANGENT", babylonjs_1.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  1903. var dataIndex = 0;
  1904. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  1905. // Tangent data for morph targets is stored as xyz delta.
  1906. // The vertexData.tangent is stored as xyzw.
  1907. // So we need to skip every fourth vertexData.tangent.
  1908. if (((index + 1) % 4) !== 0) {
  1909. data[dataIndex++] += value;
  1910. }
  1911. });
  1912. babylonMorphTarget.setTangents(data);
  1913. });
  1914. return Promise.all(promises).then(function () { });
  1915. };
  1916. GLTF2Loader._LoadTransform = function (node, babylonNode) {
  1917. var position = babylonjs_1.Vector3.Zero();
  1918. var rotation = babylonjs_1.Quaternion.Identity();
  1919. var scaling = babylonjs_1.Vector3.One();
  1920. if (node.matrix) {
  1921. var matrix = babylonjs_1.Matrix.FromArray(node.matrix);
  1922. matrix.decompose(scaling, rotation, position);
  1923. }
  1924. else {
  1925. if (node.translation) {
  1926. position = babylonjs_1.Vector3.FromArray(node.translation);
  1927. }
  1928. if (node.rotation) {
  1929. rotation = babylonjs_1.Quaternion.FromArray(node.rotation);
  1930. }
  1931. if (node.scale) {
  1932. scaling = babylonjs_1.Vector3.FromArray(node.scale);
  1933. }
  1934. }
  1935. babylonNode.position = position;
  1936. babylonNode.rotationQuaternion = rotation;
  1937. babylonNode.scaling = scaling;
  1938. };
  1939. GLTF2Loader.prototype._loadSkinAsync = function (context, node, skin) {
  1940. var _this = this;
  1941. var assignSkeleton = function (skeleton) {
  1942. _this._forEachPrimitive(node, function (babylonMesh) {
  1943. babylonMesh.skeleton = skeleton;
  1944. });
  1945. // Ignore the TRS of skinned nodes.
  1946. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  1947. node._babylonMesh.position = babylonjs_1.Vector3.Zero();
  1948. node._babylonMesh.rotationQuaternion = babylonjs_1.Quaternion.Identity();
  1949. node._babylonMesh.scaling = babylonjs_1.Vector3.One();
  1950. };
  1951. if (skin._promise) {
  1952. return skin._promise.then(function () {
  1953. assignSkeleton(skin._babylonSkeleton);
  1954. });
  1955. }
  1956. var skeletonId = "skeleton" + skin.index;
  1957. var babylonSkeleton = new babylonjs_1.Skeleton(skin.name || skeletonId, skeletonId, this.babylonScene);
  1958. skin._babylonSkeleton = babylonSkeleton;
  1959. this._loadBones(context, skin);
  1960. assignSkeleton(babylonSkeleton);
  1961. return (skin._promise = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  1962. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  1963. }));
  1964. };
  1965. GLTF2Loader.prototype._loadBones = function (context, skin) {
  1966. var babylonBones = {};
  1967. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  1968. var index = _a[_i];
  1969. var node = ArrayItem.Get(context + "/joints/" + index, this.gltf.nodes, index);
  1970. this._loadBone(node, skin, babylonBones);
  1971. }
  1972. };
  1973. GLTF2Loader.prototype._loadBone = function (node, skin, babylonBones) {
  1974. var babylonBone = babylonBones[node.index];
  1975. if (babylonBone) {
  1976. return babylonBone;
  1977. }
  1978. var babylonParentBone = null;
  1979. if (node.parent && node.parent._babylonMesh !== this._rootBabylonMesh) {
  1980. babylonParentBone = this._loadBone(node.parent, skin, babylonBones);
  1981. }
  1982. var boneIndex = skin.joints.indexOf(node.index);
  1983. babylonBone = new babylonjs_1.Bone(node.name || "joint" + node.index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  1984. babylonBones[node.index] = babylonBone;
  1985. node._babylonBones = node._babylonBones || [];
  1986. node._babylonBones.push(babylonBone);
  1987. return babylonBone;
  1988. };
  1989. GLTF2Loader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  1990. if (skin.inverseBindMatrices == undefined) {
  1991. return Promise.resolve(null);
  1992. }
  1993. var accessor = ArrayItem.Get(context + "/inverseBindMatrices", this.gltf.accessors, skin.inverseBindMatrices);
  1994. return this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor);
  1995. };
  1996. GLTF2Loader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  1997. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  1998. var babylonBone = _a[_i];
  1999. var baseMatrix = babylonjs_1.Matrix.Identity();
  2000. var boneIndex = babylonBone._index;
  2001. if (inverseBindMatricesData && boneIndex !== -1) {
  2002. babylonjs_1.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  2003. baseMatrix.invertToRef(baseMatrix);
  2004. }
  2005. var babylonParentBone = babylonBone.getParent();
  2006. if (babylonParentBone) {
  2007. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  2008. }
  2009. babylonBone.updateMatrix(baseMatrix, false, false);
  2010. babylonBone._updateDifferenceMatrix(undefined, false);
  2011. }
  2012. };
  2013. GLTF2Loader.prototype._getNodeMatrix = function (node) {
  2014. return node.matrix ?
  2015. babylonjs_1.Matrix.FromArray(node.matrix) :
  2016. babylonjs_1.Matrix.Compose(node.scale ? babylonjs_1.Vector3.FromArray(node.scale) : babylonjs_1.Vector3.One(), node.rotation ? babylonjs_1.Quaternion.FromArray(node.rotation) : babylonjs_1.Quaternion.Identity(), node.translation ? babylonjs_1.Vector3.FromArray(node.translation) : babylonjs_1.Vector3.Zero());
  2017. };
  2018. /**
  2019. * Loads a glTF camera.
  2020. * @param context The context when loading the asset
  2021. * @param camera The glTF camera property
  2022. * @param assign A function called synchronously after parsing the glTF properties
  2023. * @returns A promise that resolves with the loaded Babylon camera when the load is complete
  2024. */
  2025. GLTF2Loader.prototype.loadCameraAsync = function (context, camera, assign) {
  2026. if (assign === void 0) { assign = function () { }; }
  2027. var extensionPromise = this._extensionsLoadCameraAsync(context, camera, assign);
  2028. if (extensionPromise) {
  2029. return extensionPromise;
  2030. }
  2031. var promises = new Array();
  2032. this.logOpen(context + " " + (camera.name || ""));
  2033. var babylonCamera = new babylonjs_1.FreeCamera(camera.name || "camera" + camera.index, babylonjs_1.Vector3.Zero(), this.babylonScene, false);
  2034. babylonCamera.rotation = new babylonjs_1.Vector3(0, Math.PI, 0);
  2035. switch (camera.type) {
  2036. case "perspective" /* PERSPECTIVE */: {
  2037. var perspective = camera.perspective;
  2038. if (!perspective) {
  2039. throw new Error(context + ": Camera perspective properties are missing");
  2040. }
  2041. babylonCamera.fov = perspective.yfov;
  2042. babylonCamera.minZ = perspective.znear;
  2043. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  2044. break;
  2045. }
  2046. case "orthographic" /* ORTHOGRAPHIC */: {
  2047. if (!camera.orthographic) {
  2048. throw new Error(context + ": Camera orthographic properties are missing");
  2049. }
  2050. babylonCamera.mode = babylonjs_1.Camera.ORTHOGRAPHIC_CAMERA;
  2051. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  2052. babylonCamera.orthoRight = camera.orthographic.xmag;
  2053. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  2054. babylonCamera.orthoTop = camera.orthographic.ymag;
  2055. babylonCamera.minZ = camera.orthographic.znear;
  2056. babylonCamera.maxZ = camera.orthographic.zfar;
  2057. break;
  2058. }
  2059. default: {
  2060. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  2061. }
  2062. }
  2063. assign(babylonCamera);
  2064. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  2065. return Promise.all(promises).then(function () {
  2066. return babylonCamera;
  2067. });
  2068. };
  2069. GLTF2Loader.prototype._loadAnimationsAsync = function () {
  2070. var animations = this.gltf.animations;
  2071. if (!animations) {
  2072. return Promise.resolve();
  2073. }
  2074. var promises = new Array();
  2075. for (var index = 0; index < animations.length; index++) {
  2076. var animation = animations[index];
  2077. promises.push(this.loadAnimationAsync("#/animations/" + animation.index, animation));
  2078. }
  2079. return Promise.all(promises).then(function () { });
  2080. };
  2081. /**
  2082. * Loads a glTF animation.
  2083. * @param context The context when loading the asset
  2084. * @param animation The glTF animation property
  2085. * @returns A promise that resolves with the loaded Babylon animation group when the load is complete
  2086. */
  2087. GLTF2Loader.prototype.loadAnimationAsync = function (context, animation) {
  2088. var promise = this._extensionsLoadAnimationAsync(context, animation);
  2089. if (promise) {
  2090. return promise;
  2091. }
  2092. var babylonAnimationGroup = new babylonjs_1.AnimationGroup(animation.name || "animation" + animation.index, this.babylonScene);
  2093. animation._babylonAnimationGroup = babylonAnimationGroup;
  2094. var promises = new Array();
  2095. ArrayItem.Assign(animation.channels);
  2096. ArrayItem.Assign(animation.samplers);
  2097. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  2098. var channel = _a[_i];
  2099. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel.index, context, animation, channel, babylonAnimationGroup));
  2100. }
  2101. return Promise.all(promises).then(function () {
  2102. babylonAnimationGroup.normalize(0);
  2103. return babylonAnimationGroup;
  2104. });
  2105. };
  2106. GLTF2Loader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  2107. var _this = this;
  2108. if (channel.target.node == undefined) {
  2109. return Promise.resolve();
  2110. }
  2111. var targetNode = ArrayItem.Get(context + "/target/node", this.gltf.nodes, channel.target.node);
  2112. // Ignore animations that have no animation targets.
  2113. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  2114. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  2115. return Promise.resolve();
  2116. }
  2117. // Ignore animations targeting TRS of skinned nodes.
  2118. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  2119. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  2120. return Promise.resolve();
  2121. }
  2122. var sampler = ArrayItem.Get(context + "/sampler", animation.samplers, channel.sampler);
  2123. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  2124. var targetPath;
  2125. var animationType;
  2126. switch (channel.target.path) {
  2127. case "translation" /* TRANSLATION */: {
  2128. targetPath = "position";
  2129. animationType = babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3;
  2130. break;
  2131. }
  2132. case "rotation" /* ROTATION */: {
  2133. targetPath = "rotationQuaternion";
  2134. animationType = babylonjs_1.Animation.ANIMATIONTYPE_QUATERNION;
  2135. break;
  2136. }
  2137. case "scale" /* SCALE */: {
  2138. targetPath = "scaling";
  2139. animationType = babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3;
  2140. break;
  2141. }
  2142. case "weights" /* WEIGHTS */: {
  2143. targetPath = "influence";
  2144. animationType = babylonjs_1.Animation.ANIMATIONTYPE_FLOAT;
  2145. break;
  2146. }
  2147. default: {
  2148. throw new Error(context + "/target/path: Invalid value (" + channel.target.path + ")");
  2149. }
  2150. }
  2151. var outputBufferOffset = 0;
  2152. var getNextOutputValue;
  2153. switch (targetPath) {
  2154. case "position": {
  2155. getNextOutputValue = function () {
  2156. var value = babylonjs_1.Vector3.FromArray(data.output, outputBufferOffset);
  2157. outputBufferOffset += 3;
  2158. return value;
  2159. };
  2160. break;
  2161. }
  2162. case "rotationQuaternion": {
  2163. getNextOutputValue = function () {
  2164. var value = babylonjs_1.Quaternion.FromArray(data.output, outputBufferOffset);
  2165. outputBufferOffset += 4;
  2166. return value;
  2167. };
  2168. break;
  2169. }
  2170. case "scaling": {
  2171. getNextOutputValue = function () {
  2172. var value = babylonjs_1.Vector3.FromArray(data.output, outputBufferOffset);
  2173. outputBufferOffset += 3;
  2174. return value;
  2175. };
  2176. break;
  2177. }
  2178. case "influence": {
  2179. getNextOutputValue = function () {
  2180. var value = new Array(targetNode._numMorphTargets);
  2181. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  2182. value[i] = data.output[outputBufferOffset++];
  2183. }
  2184. return value;
  2185. };
  2186. break;
  2187. }
  2188. }
  2189. var getNextKey;
  2190. switch (data.interpolation) {
  2191. case "STEP" /* STEP */: {
  2192. getNextKey = function (frameIndex) { return ({
  2193. frame: data.input[frameIndex],
  2194. value: getNextOutputValue(),
  2195. interpolation: babylonjs_1.AnimationKeyInterpolation.STEP
  2196. }); };
  2197. break;
  2198. }
  2199. case "LINEAR" /* LINEAR */: {
  2200. getNextKey = function (frameIndex) { return ({
  2201. frame: data.input[frameIndex],
  2202. value: getNextOutputValue()
  2203. }); };
  2204. break;
  2205. }
  2206. case "CUBICSPLINE" /* CUBICSPLINE */: {
  2207. getNextKey = function (frameIndex) { return ({
  2208. frame: data.input[frameIndex],
  2209. inTangent: getNextOutputValue(),
  2210. value: getNextOutputValue(),
  2211. outTangent: getNextOutputValue()
  2212. }); };
  2213. break;
  2214. }
  2215. }
  2216. var keys = new Array(data.input.length);
  2217. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  2218. keys[frameIndex] = getNextKey(frameIndex);
  2219. }
  2220. if (targetPath === "influence") {
  2221. var _loop_2 = function (targetIndex) {
  2222. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  2223. var babylonAnimation = new babylonjs_1.Animation(animationName, targetPath, 1, animationType);
  2224. babylonAnimation.setKeys(keys.map(function (key) { return ({
  2225. frame: key.frame,
  2226. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  2227. value: key.value[targetIndex],
  2228. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  2229. }); }));
  2230. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  2231. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  2232. var babylonAnimationClone = babylonAnimation.clone();
  2233. morphTarget.animations.push(babylonAnimationClone);
  2234. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  2235. });
  2236. };
  2237. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  2238. _loop_2(targetIndex);
  2239. }
  2240. }
  2241. else {
  2242. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  2243. var babylonAnimation = new babylonjs_1.Animation(animationName, targetPath, 1, animationType);
  2244. babylonAnimation.setKeys(keys);
  2245. if (targetNode._babylonBones) {
  2246. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  2247. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  2248. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  2249. babylonAnimationTarget.animations.push(babylonAnimation);
  2250. }
  2251. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  2252. }
  2253. else {
  2254. targetNode._babylonMesh.animations.push(babylonAnimation);
  2255. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  2256. }
  2257. }
  2258. });
  2259. };
  2260. GLTF2Loader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  2261. if (sampler._data) {
  2262. return sampler._data;
  2263. }
  2264. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  2265. switch (interpolation) {
  2266. case "STEP" /* STEP */:
  2267. case "LINEAR" /* LINEAR */:
  2268. case "CUBICSPLINE" /* CUBICSPLINE */: {
  2269. break;
  2270. }
  2271. default: {
  2272. throw new Error(context + "/interpolation: Invalid value (" + sampler.interpolation + ")");
  2273. }
  2274. }
  2275. var inputAccessor = ArrayItem.Get(context + "/input", this.gltf.accessors, sampler.input);
  2276. var outputAccessor = ArrayItem.Get(context + "/output", this.gltf.accessors, sampler.output);
  2277. sampler._data = Promise.all([
  2278. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor),
  2279. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor)
  2280. ]).then(function (_a) {
  2281. var inputData = _a[0], outputData = _a[1];
  2282. return {
  2283. input: inputData,
  2284. interpolation: interpolation,
  2285. output: outputData,
  2286. };
  2287. });
  2288. return sampler._data;
  2289. };
  2290. GLTF2Loader.prototype._loadBufferAsync = function (context, buffer) {
  2291. if (buffer._data) {
  2292. return buffer._data;
  2293. }
  2294. if (!buffer.uri) {
  2295. throw new Error(context + "/uri: Value is missing");
  2296. }
  2297. buffer._data = this.loadUriAsync(context + "/uri", buffer.uri);
  2298. return buffer._data;
  2299. };
  2300. /**
  2301. * Loads a glTF buffer view.
  2302. * @param context The context when loading the asset
  2303. * @param bufferView The glTF buffer view property
  2304. * @returns A promise that resolves with the loaded data when the load is complete
  2305. */
  2306. GLTF2Loader.prototype.loadBufferViewAsync = function (context, bufferView) {
  2307. if (bufferView._data) {
  2308. return bufferView._data;
  2309. }
  2310. var buffer = ArrayItem.Get(context + "/buffer", this.gltf.buffers, bufferView.buffer);
  2311. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer.index, buffer).then(function (data) {
  2312. try {
  2313. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  2314. }
  2315. catch (e) {
  2316. throw new Error(context + ": " + e.message);
  2317. }
  2318. });
  2319. return bufferView._data;
  2320. };
  2321. GLTF2Loader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  2322. if (accessor.type !== "SCALAR" /* SCALAR */) {
  2323. throw new Error(context + "/type: Invalid value " + accessor.type);
  2324. }
  2325. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  2326. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  2327. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  2328. throw new Error(context + "/componentType: Invalid value " + accessor.componentType);
  2329. }
  2330. if (accessor._data) {
  2331. return accessor._data;
  2332. }
  2333. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  2334. accessor._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  2335. return GLTF2Loader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  2336. });
  2337. return accessor._data;
  2338. };
  2339. GLTF2Loader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  2340. // TODO: support normalized and stride
  2341. var _this = this;
  2342. if (accessor.componentType !== 5126 /* FLOAT */) {
  2343. throw new Error("Invalid component type " + accessor.componentType);
  2344. }
  2345. if (accessor._data) {
  2346. return accessor._data;
  2347. }
  2348. var numComponents = GLTF2Loader._GetNumComponents(context, accessor.type);
  2349. var length = numComponents * accessor.count;
  2350. if (accessor.bufferView == undefined) {
  2351. accessor._data = Promise.resolve(new Float32Array(length));
  2352. }
  2353. else {
  2354. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  2355. accessor._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  2356. return GLTF2Loader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  2357. });
  2358. }
  2359. if (accessor.sparse) {
  2360. var sparse_1 = accessor.sparse;
  2361. accessor._data = accessor._data.then(function (data) {
  2362. var indicesBufferView = ArrayItem.Get(context + "/sparse/indices/bufferView", _this.gltf.bufferViews, sparse_1.indices.bufferView);
  2363. var valuesBufferView = ArrayItem.Get(context + "/sparse/values/bufferView", _this.gltf.bufferViews, sparse_1.values.bufferView);
  2364. return Promise.all([
  2365. _this.loadBufferViewAsync("#/bufferViews/" + indicesBufferView.index, indicesBufferView),
  2366. _this.loadBufferViewAsync("#/bufferViews/" + valuesBufferView.index, valuesBufferView)
  2367. ]).then(function (_a) {
  2368. var indicesData = _a[0], valuesData = _a[1];
  2369. var indices = GLTF2Loader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  2370. var values = GLTF2Loader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  2371. var valuesIndex = 0;
  2372. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  2373. var dataIndex = indices[indicesIndex] * numComponents;
  2374. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  2375. data[dataIndex++] = values[valuesIndex++];
  2376. }
  2377. }
  2378. return data;
  2379. });
  2380. });
  2381. }
  2382. return accessor._data;
  2383. };
  2384. GLTF2Loader.prototype._loadVertexBufferViewAsync = function (bufferView, kind) {
  2385. var _this = this;
  2386. if (bufferView._babylonBuffer) {
  2387. return bufferView._babylonBuffer;
  2388. }
  2389. bufferView._babylonBuffer = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  2390. return new babylonjs_1.Buffer(_this.babylonScene.getEngine(), data, false);
  2391. });
  2392. return bufferView._babylonBuffer;
  2393. };
  2394. GLTF2Loader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  2395. var _this = this;
  2396. if (accessor._babylonVertexBuffer) {
  2397. return accessor._babylonVertexBuffer;
  2398. }
  2399. if (accessor.sparse) {
  2400. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  2401. return new babylonjs_1.VertexBuffer(_this.babylonScene.getEngine(), data, kind, false);
  2402. });
  2403. }
  2404. // HACK: If byte offset is not a multiple of component type byte length then load as a float array instead of using Babylon buffers.
  2405. else if (accessor.byteOffset && accessor.byteOffset % babylonjs_1.VertexBuffer.GetTypeByteLength(accessor.componentType) !== 0) {
  2406. babylonjs_1.Tools.Warn("Accessor byte offset is not a multiple of component type byte length");
  2407. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  2408. return new babylonjs_1.VertexBuffer(_this.babylonScene.getEngine(), data, kind, false);
  2409. });
  2410. }
  2411. else {
  2412. var bufferView_1 = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  2413. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync(bufferView_1, kind).then(function (babylonBuffer) {
  2414. var size = GLTF2Loader._GetNumComponents(context, accessor.type);
  2415. return new babylonjs_1.VertexBuffer(_this.babylonScene.getEngine(), babylonBuffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  2416. });
  2417. }
  2418. return accessor._babylonVertexBuffer;
  2419. };
  2420. GLTF2Loader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, properties, babylonMaterial) {
  2421. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  2422. throw new Error(context + ": Material type not supported");
  2423. }
  2424. var promises = new Array();
  2425. if (properties) {
  2426. if (properties.baseColorFactor) {
  2427. babylonMaterial.albedoColor = babylonjs_1.Color3.FromArray(properties.baseColorFactor);
  2428. babylonMaterial.alpha = properties.baseColorFactor[3];
  2429. }
  2430. else {
  2431. babylonMaterial.albedoColor = babylonjs_1.Color3.White();
  2432. }
  2433. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  2434. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  2435. if (properties.baseColorTexture) {
  2436. promises.push(this.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  2437. babylonMaterial.albedoTexture = texture;
  2438. }));
  2439. }
  2440. if (properties.metallicRoughnessTexture) {
  2441. promises.push(this.loadTextureInfoAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  2442. babylonMaterial.metallicTexture = texture;
  2443. }));
  2444. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  2445. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  2446. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  2447. }
  2448. }
  2449. return Promise.all(promises).then(function () { });
  2450. };
  2451. /** @hidden */
  2452. GLTF2Loader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  2453. if (assign === void 0) { assign = function () { }; }
  2454. var extensionPromise = this._extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign);
  2455. if (extensionPromise) {
  2456. return extensionPromise;
  2457. }
  2458. material._babylonData = material._babylonData || {};
  2459. var babylonData = material._babylonData[babylonDrawMode];
  2460. if (!babylonData) {
  2461. this.logOpen(context + " " + (material.name || ""));
  2462. var babylonMaterial = this.createMaterial(context, material, babylonDrawMode);
  2463. babylonData = {
  2464. material: babylonMaterial,
  2465. meshes: [],
  2466. promise: this.loadMaterialPropertiesAsync(context, material, babylonMaterial)
  2467. };
  2468. material._babylonData[babylonDrawMode] = babylonData;
  2469. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  2470. this.logClose();
  2471. }
  2472. babylonData.meshes.push(babylonMesh);
  2473. babylonMesh.onDisposeObservable.addOnce(function () {
  2474. var index = babylonData.meshes.indexOf(babylonMesh);
  2475. if (index !== -1) {
  2476. babylonData.meshes.splice(index, 1);
  2477. }
  2478. });
  2479. assign(babylonData.material);
  2480. return babylonData.promise.then(function () {
  2481. return babylonData.material;
  2482. });
  2483. };
  2484. GLTF2Loader.prototype._createDefaultMaterial = function (name, babylonDrawMode) {
  2485. var babylonMaterial = new babylonjs_1.PBRMaterial(name, this.babylonScene);
  2486. babylonMaterial.sideOrientation = this.babylonScene.useRightHandedSystem ? babylonjs_1.Material.CounterClockWiseSideOrientation : babylonjs_1.Material.ClockWiseSideOrientation;
  2487. babylonMaterial.fillMode = babylonDrawMode;
  2488. babylonMaterial.enableSpecularAntiAliasing = true;
  2489. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  2490. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  2491. babylonMaterial.transparencyMode = babylonjs_1.PBRMaterial.PBRMATERIAL_OPAQUE;
  2492. babylonMaterial.metallic = 1;
  2493. babylonMaterial.roughness = 1;
  2494. return babylonMaterial;
  2495. };
  2496. /**
  2497. * Creates a Babylon material from a glTF material.
  2498. * @param context The context when loading the asset
  2499. * @param material The glTF material property
  2500. * @param babylonDrawMode The draw mode for the Babylon material
  2501. * @returns The Babylon material
  2502. */
  2503. GLTF2Loader.prototype.createMaterial = function (context, material, babylonDrawMode) {
  2504. var extensionPromise = this._extensionsCreateMaterial(context, material, babylonDrawMode);
  2505. if (extensionPromise) {
  2506. return extensionPromise;
  2507. }
  2508. var name = material.name || "material" + material.index;
  2509. return this._createDefaultMaterial(name, babylonDrawMode);
  2510. };
  2511. /**
  2512. * Loads properties from a glTF material into a Babylon material.
  2513. * @param context The context when loading the asset
  2514. * @param material The glTF material property
  2515. * @param babylonMaterial The Babylon material
  2516. * @returns A promise that resolves when the load is complete
  2517. */
  2518. GLTF2Loader.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  2519. var extensionPromise = this._extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial);
  2520. if (extensionPromise) {
  2521. return extensionPromise;
  2522. }
  2523. var promises = new Array();
  2524. promises.push(this.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  2525. if (material.pbrMetallicRoughness) {
  2526. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context + "/pbrMetallicRoughness", material.pbrMetallicRoughness, babylonMaterial));
  2527. }
  2528. this.loadMaterialAlphaProperties(context, material, babylonMaterial);
  2529. return Promise.all(promises).then(function () { });
  2530. };
  2531. /**
  2532. * Loads the normal, occlusion, and emissive properties from a glTF material into a Babylon material.
  2533. * @param context The context when loading the asset
  2534. * @param material The glTF material property
  2535. * @param babylonMaterial The Babylon material
  2536. * @returns A promise that resolves when the load is complete
  2537. */
  2538. GLTF2Loader.prototype.loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  2539. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  2540. throw new Error(context + ": Material type not supported");
  2541. }
  2542. var promises = new Array();
  2543. babylonMaterial.emissiveColor = material.emissiveFactor ? babylonjs_1.Color3.FromArray(material.emissiveFactor) : new babylonjs_1.Color3(0, 0, 0);
  2544. if (material.doubleSided) {
  2545. babylonMaterial.backFaceCulling = false;
  2546. babylonMaterial.twoSidedLighting = true;
  2547. }
  2548. if (material.normalTexture) {
  2549. promises.push(this.loadTextureInfoAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  2550. babylonMaterial.bumpTexture = texture;
  2551. }));
  2552. babylonMaterial.invertNormalMapX = !this.babylonScene.useRightHandedSystem;
  2553. babylonMaterial.invertNormalMapY = this.babylonScene.useRightHandedSystem;
  2554. if (material.normalTexture.scale != undefined) {
  2555. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  2556. }
  2557. }
  2558. if (material.occlusionTexture) {
  2559. promises.push(this.loadTextureInfoAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  2560. babylonMaterial.ambientTexture = texture;
  2561. }));
  2562. babylonMaterial.useAmbientInGrayScale = true;
  2563. if (material.occlusionTexture.strength != undefined) {
  2564. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  2565. }
  2566. }
  2567. if (material.emissiveTexture) {
  2568. promises.push(this.loadTextureInfoAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  2569. babylonMaterial.emissiveTexture = texture;
  2570. }));
  2571. }
  2572. return Promise.all(promises).then(function () { });
  2573. };
  2574. /**
  2575. * Loads the alpha properties from a glTF material into a Babylon material.
  2576. * Must be called after the setting the albedo texture of the Babylon material when the material has an albedo texture.
  2577. * @param context The context when loading the asset
  2578. * @param material The glTF material property
  2579. * @param babylonMaterial The Babylon material
  2580. */
  2581. GLTF2Loader.prototype.loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  2582. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  2583. throw new Error(context + ": Material type not supported");
  2584. }
  2585. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  2586. switch (alphaMode) {
  2587. case "OPAQUE" /* OPAQUE */: {
  2588. babylonMaterial.transparencyMode = babylonjs_1.PBRMaterial.PBRMATERIAL_OPAQUE;
  2589. break;
  2590. }
  2591. case "MASK" /* MASK */: {
  2592. babylonMaterial.transparencyMode = babylonjs_1.PBRMaterial.PBRMATERIAL_ALPHATEST;
  2593. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  2594. if (babylonMaterial.albedoTexture) {
  2595. babylonMaterial.albedoTexture.hasAlpha = true;
  2596. }
  2597. break;
  2598. }
  2599. case "BLEND" /* BLEND */: {
  2600. babylonMaterial.transparencyMode = babylonjs_1.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  2601. if (babylonMaterial.albedoTexture) {
  2602. babylonMaterial.albedoTexture.hasAlpha = true;
  2603. babylonMaterial.useAlphaFromAlbedoTexture = true;
  2604. }
  2605. break;
  2606. }
  2607. default: {
  2608. throw new Error(context + "/alphaMode: Invalid value (" + material.alphaMode + ")");
  2609. }
  2610. }
  2611. };
  2612. /**
  2613. * Loads a glTF texture info.
  2614. * @param context The context when loading the asset
  2615. * @param textureInfo The glTF texture info property
  2616. * @param assign A function called synchronously after parsing the glTF properties
  2617. * @returns A promise that resolves with the loaded Babylon texture when the load is complete
  2618. */
  2619. GLTF2Loader.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) {
  2620. if (assign === void 0) { assign = function () { }; }
  2621. var extensionPromise = this._extensionsLoadTextureInfoAsync(context, textureInfo, assign);
  2622. if (extensionPromise) {
  2623. return extensionPromise;
  2624. }
  2625. this.logOpen("" + context);
  2626. var texture = ArrayItem.Get(context + "/index", this.gltf.textures, textureInfo.index);
  2627. var promise = this._loadTextureAsync("#/textures/" + textureInfo.index, texture, function (babylonTexture) {
  2628. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  2629. assign(babylonTexture);
  2630. });
  2631. this.logClose();
  2632. return promise;
  2633. };
  2634. GLTF2Loader.prototype._loadTextureAsync = function (context, texture, assign) {
  2635. var _this = this;
  2636. if (assign === void 0) { assign = function () { }; }
  2637. var promises = new Array();
  2638. this.logOpen(context + " " + (texture.name || ""));
  2639. var sampler = (texture.sampler == undefined ? GLTF2Loader._DefaultSampler : ArrayItem.Get(context + "/sampler", this.gltf.samplers, texture.sampler));
  2640. var samplerData = this._loadSampler("#/samplers/" + sampler.index, sampler);
  2641. var deferred = new babylonjs_1.Deferred();
  2642. var babylonTexture = new babylonjs_1.Texture(null, this.babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  2643. if (!_this._disposed) {
  2644. deferred.resolve();
  2645. }
  2646. }, function (message, exception) {
  2647. if (!_this._disposed) {
  2648. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  2649. }
  2650. });
  2651. promises.push(deferred.promise);
  2652. babylonTexture.name = texture.name || "texture" + texture.index;
  2653. babylonTexture.wrapU = samplerData.wrapU;
  2654. babylonTexture.wrapV = samplerData.wrapV;
  2655. var image = ArrayItem.Get(context + "/source", this.gltf.images, texture.source);
  2656. promises.push(this.loadImageAsync("#/images/" + image.index, image).then(function (data) {
  2657. var name = image.uri || _this._fileName + "#image" + image.index;
  2658. var dataUrl = "data:" + _this._uniqueRootUrl + name;
  2659. babylonTexture.updateURL(dataUrl, new Blob([data], { type: image.mimeType }));
  2660. }));
  2661. assign(babylonTexture);
  2662. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  2663. this.logClose();
  2664. return Promise.all(promises).then(function () {
  2665. return babylonTexture;
  2666. });
  2667. };
  2668. GLTF2Loader.prototype._loadSampler = function (context, sampler) {
  2669. if (!sampler._data) {
  2670. sampler._data = {
  2671. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  2672. samplingMode: GLTF2Loader._GetTextureSamplingMode(context, sampler),
  2673. wrapU: GLTF2Loader._GetTextureWrapMode(context + "/wrapS", sampler.wrapS),
  2674. wrapV: GLTF2Loader._GetTextureWrapMode(context + "/wrapT", sampler.wrapT)
  2675. };
  2676. }
  2677. return sampler._data;
  2678. };
  2679. /**
  2680. * Loads a glTF image.
  2681. * @param context The context when loading the asset
  2682. * @param image The glTF image property
  2683. * @returns A promise that resolves with the loaded data when the load is complete
  2684. */
  2685. GLTF2Loader.prototype.loadImageAsync = function (context, image) {
  2686. if (!image._data) {
  2687. this.logOpen(context + " " + (image.name || ""));
  2688. if (image.uri) {
  2689. image._data = this.loadUriAsync(context + "/uri", image.uri);
  2690. }
  2691. else {
  2692. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, image.bufferView);
  2693. image._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView);
  2694. }
  2695. this.logClose();
  2696. }
  2697. return image._data;
  2698. };
  2699. /**
  2700. * Loads a glTF uri.
  2701. * @param context The context when loading the asset
  2702. * @param uri The base64 or relative uri
  2703. * @returns A promise that resolves with the loaded data when the load is complete
  2704. */
  2705. GLTF2Loader.prototype.loadUriAsync = function (context, uri) {
  2706. var _this = this;
  2707. var extensionPromise = this._extensionsLoadUriAsync(context, uri);
  2708. if (extensionPromise) {
  2709. return extensionPromise;
  2710. }
  2711. if (!GLTF2Loader._ValidateUri(uri)) {
  2712. throw new Error(context + ": '" + uri + "' is invalid");
  2713. }
  2714. if (babylonjs_1.Tools.IsBase64(uri)) {
  2715. var data = new Uint8Array(babylonjs_1.Tools.DecodeBase64(uri));
  2716. this.log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)");
  2717. return Promise.resolve(data);
  2718. }
  2719. this.log("Loading " + uri);
  2720. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  2721. return new Promise(function (resolve, reject) {
  2722. if (!_this._disposed) {
  2723. var request_1 = babylonjs_1.Tools.LoadFile(url, function (fileData) {
  2724. if (!_this._disposed) {
  2725. var data = new Uint8Array(fileData);
  2726. _this.log("Loaded " + uri + " (" + data.length + " bytes)");
  2727. resolve(data);
  2728. }
  2729. }, function (event) {
  2730. if (!_this._disposed) {
  2731. if (request_1) {
  2732. request_1._lengthComputable = event.lengthComputable;
  2733. request_1._loaded = event.loaded;
  2734. request_1._total = event.total;
  2735. }
  2736. if (_this._state === glTFFileLoader_1.GLTFLoaderState.LOADING) {
  2737. try {
  2738. _this._onProgress();
  2739. }
  2740. catch (e) {
  2741. reject(e);
  2742. }
  2743. }
  2744. }
  2745. }, _this.babylonScene.offlineProvider, true, function (request, exception) {
  2746. if (!_this._disposed) {
  2747. reject(new babylonjs_1.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  2748. }
  2749. });
  2750. _this._requests.push(request_1);
  2751. }
  2752. });
  2753. });
  2754. };
  2755. GLTF2Loader.prototype._onProgress = function () {
  2756. if (!this._progressCallback) {
  2757. return;
  2758. }
  2759. var lengthComputable = true;
  2760. var loaded = 0;
  2761. var total = 0;
  2762. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  2763. var request = _a[_i];
  2764. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  2765. return;
  2766. }
  2767. lengthComputable = lengthComputable && request._lengthComputable;
  2768. loaded += request._loaded;
  2769. total += request._total;
  2770. }
  2771. this._progressCallback(new babylonjs_1.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  2772. };
  2773. GLTF2Loader._GetTextureWrapMode = function (context, mode) {
  2774. // Set defaults if undefined
  2775. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  2776. switch (mode) {
  2777. case 33071 /* CLAMP_TO_EDGE */: return babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  2778. case 33648 /* MIRRORED_REPEAT */: return babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  2779. case 10497 /* REPEAT */: return babylonjs_1.Texture.WRAP_ADDRESSMODE;
  2780. default:
  2781. babylonjs_1.Tools.Warn(context + ": Invalid value (" + mode + ")");
  2782. return babylonjs_1.Texture.WRAP_ADDRESSMODE;
  2783. }
  2784. };
  2785. GLTF2Loader._GetTextureSamplingMode = function (context, sampler) {
  2786. // Set defaults if undefined
  2787. var magFilter = sampler.magFilter == undefined ? 9729 /* LINEAR */ : sampler.magFilter;
  2788. var minFilter = sampler.minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : sampler.minFilter;
  2789. if (magFilter === 9729 /* LINEAR */) {
  2790. switch (minFilter) {
  2791. case 9728 /* NEAREST */: return babylonjs_1.Texture.LINEAR_NEAREST;
  2792. case 9729 /* LINEAR */: return babylonjs_1.Texture.LINEAR_LINEAR;
  2793. case 9984 /* NEAREST_MIPMAP_NEAREST */: return babylonjs_1.Texture.LINEAR_NEAREST_MIPNEAREST;
  2794. case 9985 /* LINEAR_MIPMAP_NEAREST */: return babylonjs_1.Texture.LINEAR_LINEAR_MIPNEAREST;
  2795. case 9986 /* NEAREST_MIPMAP_LINEAR */: return babylonjs_1.Texture.LINEAR_NEAREST_MIPLINEAR;
  2796. case 9987 /* LINEAR_MIPMAP_LINEAR */: return babylonjs_1.Texture.LINEAR_LINEAR_MIPLINEAR;
  2797. default:
  2798. babylonjs_1.Tools.Warn(context + "/minFilter: Invalid value (" + minFilter + ")");
  2799. return babylonjs_1.Texture.LINEAR_LINEAR_MIPLINEAR;
  2800. }
  2801. }
  2802. else {
  2803. if (magFilter !== 9728 /* NEAREST */) {
  2804. babylonjs_1.Tools.Warn(context + "/magFilter: Invalid value (" + magFilter + ")");
  2805. }
  2806. switch (minFilter) {
  2807. case 9728 /* NEAREST */: return babylonjs_1.Texture.NEAREST_NEAREST;
  2808. case 9729 /* LINEAR */: return babylonjs_1.Texture.NEAREST_LINEAR;
  2809. case 9984 /* NEAREST_MIPMAP_NEAREST */: return babylonjs_1.Texture.NEAREST_NEAREST_MIPNEAREST;
  2810. case 9985 /* LINEAR_MIPMAP_NEAREST */: return babylonjs_1.Texture.NEAREST_LINEAR_MIPNEAREST;
  2811. case 9986 /* NEAREST_MIPMAP_LINEAR */: return babylonjs_1.Texture.NEAREST_NEAREST_MIPLINEAR;
  2812. case 9987 /* LINEAR_MIPMAP_LINEAR */: return babylonjs_1.Texture.NEAREST_LINEAR_MIPLINEAR;
  2813. default:
  2814. babylonjs_1.Tools.Warn(context + "/minFilter: Invalid value (" + minFilter + ")");
  2815. return babylonjs_1.Texture.NEAREST_NEAREST_MIPNEAREST;
  2816. }
  2817. }
  2818. };
  2819. GLTF2Loader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  2820. var buffer = bufferView.buffer;
  2821. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  2822. try {
  2823. switch (componentType) {
  2824. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  2825. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  2826. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  2827. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  2828. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  2829. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  2830. default: throw new Error("Invalid component type " + componentType);
  2831. }
  2832. }
  2833. catch (e) {
  2834. throw new Error(context + ": " + e);
  2835. }
  2836. };
  2837. GLTF2Loader._GetNumComponents = function (context, type) {
  2838. switch (type) {
  2839. case "SCALAR": return 1;
  2840. case "VEC2": return 2;
  2841. case "VEC3": return 3;
  2842. case "VEC4": return 4;
  2843. case "MAT2": return 4;
  2844. case "MAT3": return 9;
  2845. case "MAT4": return 16;
  2846. }
  2847. throw new Error(context + ": Invalid type (" + type + ")");
  2848. };
  2849. GLTF2Loader._ValidateUri = function (uri) {
  2850. return (babylonjs_1.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  2851. };
  2852. GLTF2Loader._GetDrawMode = function (context, mode) {
  2853. if (mode == undefined) {
  2854. mode = 4 /* TRIANGLES */;
  2855. }
  2856. switch (mode) {
  2857. case 0 /* POINTS */: return babylonjs_1.Material.PointListDrawMode;
  2858. case 1 /* LINES */: return babylonjs_1.Material.LineListDrawMode;
  2859. case 2 /* LINE_LOOP */: return babylonjs_1.Material.LineLoopDrawMode;
  2860. case 3 /* LINE_STRIP */: return babylonjs_1.Material.LineStripDrawMode;
  2861. case 4 /* TRIANGLES */: return babylonjs_1.Material.TriangleFillMode;
  2862. case 5 /* TRIANGLE_STRIP */: return babylonjs_1.Material.TriangleStripDrawMode;
  2863. case 6 /* TRIANGLE_FAN */: return babylonjs_1.Material.TriangleFanDrawMode;
  2864. }
  2865. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  2866. };
  2867. GLTF2Loader.prototype._compileMaterialsAsync = function () {
  2868. var _this = this;
  2869. this._parent._startPerformanceCounter("Compile materials");
  2870. var promises = new Array();
  2871. if (this.gltf.materials) {
  2872. for (var _i = 0, _a = this.gltf.materials; _i < _a.length; _i++) {
  2873. var material = _a[_i];
  2874. if (material._babylonData) {
  2875. for (var babylonDrawMode in material._babylonData) {
  2876. var babylonData = material._babylonData[babylonDrawMode];
  2877. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  2878. var babylonMesh = _c[_b];
  2879. // Ensure nonUniformScaling is set if necessary.
  2880. babylonMesh.computeWorldMatrix(true);
  2881. var babylonMaterial = babylonData.material;
  2882. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  2883. if (this._parent.useClipPlane) {
  2884. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  2885. }
  2886. }
  2887. }
  2888. }
  2889. }
  2890. }
  2891. return Promise.all(promises).then(function () {
  2892. _this._parent._endPerformanceCounter("Compile materials");
  2893. });
  2894. };
  2895. GLTF2Loader.prototype._compileShadowGeneratorsAsync = function () {
  2896. var _this = this;
  2897. this._parent._startPerformanceCounter("Compile shadow generators");
  2898. var promises = new Array();
  2899. var lights = this.babylonScene.lights;
  2900. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  2901. var light = lights_1[_i];
  2902. var generator = light.getShadowGenerator();
  2903. if (generator) {
  2904. promises.push(generator.forceCompilationAsync());
  2905. }
  2906. }
  2907. return Promise.all(promises).then(function () {
  2908. _this._parent._endPerformanceCounter("Compile shadow generators");
  2909. });
  2910. };
  2911. GLTF2Loader.prototype._forEachExtensions = function (action) {
  2912. for (var _i = 0, _a = GLTF2Loader._ExtensionNames; _i < _a.length; _i++) {
  2913. var name_4 = _a[_i];
  2914. var extension = this._extensions[name_4];
  2915. if (extension.enabled) {
  2916. action(extension);
  2917. }
  2918. }
  2919. };
  2920. GLTF2Loader.prototype._applyExtensions = function (property, actionAsync) {
  2921. for (var _i = 0, _a = GLTF2Loader._ExtensionNames; _i < _a.length; _i++) {
  2922. var name_5 = _a[_i];
  2923. var extension = this._extensions[name_5];
  2924. if (extension.enabled) {
  2925. var loaderProperty = property;
  2926. loaderProperty._activeLoaderExtensions = loaderProperty._activeLoaderExtensions || {};
  2927. var activeLoaderExtensions = loaderProperty._activeLoaderExtensions;
  2928. if (!activeLoaderExtensions[name_5]) {
  2929. activeLoaderExtensions[name_5] = true;
  2930. try {
  2931. var result = actionAsync(extension);
  2932. if (result) {
  2933. return result;
  2934. }
  2935. }
  2936. finally {
  2937. delete activeLoaderExtensions[name_5];
  2938. }
  2939. }
  2940. }
  2941. }
  2942. return null;
  2943. };
  2944. GLTF2Loader.prototype._extensionsOnLoading = function () {
  2945. this._forEachExtensions(function (extension) { return extension.onLoading && extension.onLoading(); });
  2946. };
  2947. GLTF2Loader.prototype._extensionsOnReady = function () {
  2948. this._forEachExtensions(function (extension) { return extension.onReady && extension.onReady(); });
  2949. };
  2950. GLTF2Loader.prototype._extensionsLoadSceneAsync = function (context, scene) {
  2951. return this._applyExtensions(scene, function (extension) { return extension.loadSceneAsync && extension.loadSceneAsync(context, scene); });
  2952. };
  2953. GLTF2Loader.prototype._extensionsLoadNodeAsync = function (context, node, assign) {
  2954. return this._applyExtensions(node, function (extension) { return extension.loadNodeAsync && extension.loadNodeAsync(context, node, assign); });
  2955. };
  2956. GLTF2Loader.prototype._extensionsLoadCameraAsync = function (context, camera, assign) {
  2957. return this._applyExtensions(camera, function (extension) { return extension.loadCameraAsync && extension.loadCameraAsync(context, camera, assign); });
  2958. };
  2959. GLTF2Loader.prototype._extensionsLoadVertexDataAsync = function (context, primitive, babylonMesh) {
  2960. return this._applyExtensions(primitive, function (extension) { return extension._loadVertexDataAsync && extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  2961. };
  2962. GLTF2Loader.prototype._extensionsLoadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  2963. return this._applyExtensions(material, function (extension) { return extension._loadMaterialAsync && extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  2964. };
  2965. GLTF2Loader.prototype._extensionsCreateMaterial = function (context, material, babylonDrawMode) {
  2966. return this._applyExtensions({}, function (extension) { return extension.createMaterial && extension.createMaterial(context, material, babylonDrawMode); });
  2967. };
  2968. GLTF2Loader.prototype._extensionsLoadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  2969. return this._applyExtensions(material, function (extension) { return extension.loadMaterialPropertiesAsync && extension.loadMaterialPropertiesAsync(context, material, babylonMaterial); });
  2970. };
  2971. GLTF2Loader.prototype._extensionsLoadTextureInfoAsync = function (context, textureInfo, assign) {
  2972. return this._applyExtensions(textureInfo, function (extension) { return extension.loadTextureInfoAsync && extension.loadTextureInfoAsync(context, textureInfo, assign); });
  2973. };
  2974. GLTF2Loader.prototype._extensionsLoadAnimationAsync = function (context, animation) {
  2975. return this._applyExtensions(animation, function (extension) { return extension.loadAnimationAsync && extension.loadAnimationAsync(context, animation); });
  2976. };
  2977. GLTF2Loader.prototype._extensionsLoadUriAsync = function (context, uri) {
  2978. return this._applyExtensions({}, function (extension) { return extension._loadUriAsync && extension._loadUriAsync(context, uri); });
  2979. };
  2980. /**
  2981. * Helper method called by a loader extension to load an glTF extension.
  2982. * @param context The context when loading the asset
  2983. * @param property The glTF property to load the extension from
  2984. * @param extensionName The name of the extension to load
  2985. * @param actionAsync The action to run
  2986. * @returns The promise returned by actionAsync or null if the extension does not exist
  2987. */
  2988. GLTF2Loader.LoadExtensionAsync = function (context, property, extensionName, actionAsync) {
  2989. if (!property.extensions) {
  2990. return null;
  2991. }
  2992. var extensions = property.extensions;
  2993. var extension = extensions[extensionName];
  2994. if (!extension) {
  2995. return null;
  2996. }
  2997. return actionAsync(context + "/extensions/" + extensionName, extension);
  2998. };
  2999. /**
  3000. * Helper method called by a loader extension to load a glTF extra.
  3001. * @param context The context when loading the asset
  3002. * @param property The glTF property to load the extra from
  3003. * @param extensionName The name of the extension to load
  3004. * @param actionAsync The action to run
  3005. * @returns The promise returned by actionAsync or null if the extra does not exist
  3006. */
  3007. GLTF2Loader.LoadExtraAsync = function (context, property, extensionName, actionAsync) {
  3008. if (!property.extras) {
  3009. return null;
  3010. }
  3011. var extras = property.extras;
  3012. var extra = extras[extensionName];
  3013. if (!extra) {
  3014. return null;
  3015. }
  3016. return actionAsync(context + "/extras/" + extensionName, extra);
  3017. };
  3018. /**
  3019. * Increments the indentation level and logs a message.
  3020. * @param message The message to log
  3021. */
  3022. GLTF2Loader.prototype.logOpen = function (message) {
  3023. this._parent._logOpen(message);
  3024. };
  3025. /**
  3026. * Decrements the indentation level.
  3027. */
  3028. GLTF2Loader.prototype.logClose = function () {
  3029. this._parent._logClose();
  3030. };
  3031. /**
  3032. * Logs a message
  3033. * @param message The message to log
  3034. */
  3035. GLTF2Loader.prototype.log = function (message) {
  3036. this._parent._log(message);
  3037. };
  3038. /**
  3039. * Starts a performance counter.
  3040. * @param counterName The name of the performance counter
  3041. */
  3042. GLTF2Loader.prototype.startPerformanceCounter = function (counterName) {
  3043. this._parent._startPerformanceCounter(counterName);
  3044. };
  3045. /**
  3046. * Ends a performance counter.
  3047. * @param counterName The name of the performance counter
  3048. */
  3049. GLTF2Loader.prototype.endPerformanceCounter = function (counterName) {
  3050. this._parent._endPerformanceCounter(counterName);
  3051. };
  3052. GLTF2Loader._DefaultSampler = { index: -1 };
  3053. GLTF2Loader._ExtensionNames = new Array();
  3054. GLTF2Loader._ExtensionFactories = {};
  3055. return GLTF2Loader;
  3056. }());
  3057. exports.GLTF2Loader = GLTF2Loader;
  3058. glTFFileLoader_1.GLTFFileLoader._CreateGLTF2Loader = function (parent) { return new GLTF2Loader(parent); };
  3059. /***/ }),
  3060. /***/ "./src/glTF/2.0/glTFLoaderExtension.ts":
  3061. /*!*********************************************!*\
  3062. !*** ./src/glTF/2.0/glTFLoaderExtension.ts ***!
  3063. \*********************************************/
  3064. /*! no static exports found */
  3065. /***/ (function(module, exports, __webpack_require__) {
  3066. "use strict";
  3067. Object.defineProperty(exports, "__esModule", { value: true });
  3068. /** @hidden */
  3069. exports.__IGLTFLoaderExtensionV2 = 0; // I am here to allow dts to be created
  3070. /***/ }),
  3071. /***/ "./src/glTF/2.0/glTFLoaderInterfaces.ts":
  3072. /*!**********************************************!*\
  3073. !*** ./src/glTF/2.0/glTFLoaderInterfaces.ts ***!
  3074. \**********************************************/
  3075. /*! no static exports found */
  3076. /***/ (function(module, exports, __webpack_require__) {
  3077. "use strict";
  3078. Object.defineProperty(exports, "__esModule", { value: true });
  3079. /** @hidden */
  3080. exports.__IGLTFLoaderInterfacesV2 = 0; // I am here to allow dts to be created
  3081. /***/ }),
  3082. /***/ "./src/glTF/2.0/index.ts":
  3083. /*!*******************************!*\
  3084. !*** ./src/glTF/2.0/index.ts ***!
  3085. \*******************************/
  3086. /*! no static exports found */
  3087. /***/ (function(module, exports, __webpack_require__) {
  3088. "use strict";
  3089. function __export(m) {
  3090. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  3091. }
  3092. Object.defineProperty(exports, "__esModule", { value: true });
  3093. __export(__webpack_require__(/*! ./glTF2Loader */ "./src/glTF/2.0/glTF2Loader.ts"));
  3094. __export(__webpack_require__(/*! ./glTFLoaderExtension */ "./src/glTF/2.0/glTFLoaderExtension.ts"));
  3095. __export(__webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/2.0/glTFLoaderInterfaces.ts"));
  3096. __export(__webpack_require__(/*! ./Extensions */ "./src/glTF/2.0/Extensions/index.ts"));
  3097. /***/ }),
  3098. /***/ "./src/glTF/glTFFileLoader.ts":
  3099. /*!************************************!*\
  3100. !*** ./src/glTF/glTFFileLoader.ts ***!
  3101. \************************************/
  3102. /*! no static exports found */
  3103. /***/ (function(module, exports, __webpack_require__) {
  3104. "use strict";
  3105. Object.defineProperty(exports, "__esModule", { value: true });
  3106. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  3107. /**
  3108. * Mode that determines the coordinate system to use.
  3109. */
  3110. var GLTFLoaderCoordinateSystemMode;
  3111. (function (GLTFLoaderCoordinateSystemMode) {
  3112. /**
  3113. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  3114. */
  3115. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  3116. /**
  3117. * Sets the useRightHandedSystem flag on the scene.
  3118. */
  3119. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  3120. })(GLTFLoaderCoordinateSystemMode = exports.GLTFLoaderCoordinateSystemMode || (exports.GLTFLoaderCoordinateSystemMode = {}));
  3121. /**
  3122. * Mode that determines what animations will start.
  3123. */
  3124. var GLTFLoaderAnimationStartMode;
  3125. (function (GLTFLoaderAnimationStartMode) {
  3126. /**
  3127. * No animation will start.
  3128. */
  3129. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  3130. /**
  3131. * The first animation will start.
  3132. */
  3133. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  3134. /**
  3135. * All animations will start.
  3136. */
  3137. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  3138. })(GLTFLoaderAnimationStartMode = exports.GLTFLoaderAnimationStartMode || (exports.GLTFLoaderAnimationStartMode = {}));
  3139. /**
  3140. * Loader state.
  3141. */
  3142. var GLTFLoaderState;
  3143. (function (GLTFLoaderState) {
  3144. /**
  3145. * The asset is loading.
  3146. */
  3147. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  3148. /**
  3149. * The asset is ready for rendering.
  3150. */
  3151. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  3152. /**
  3153. * The asset is completely loaded.
  3154. */
  3155. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  3156. })(GLTFLoaderState = exports.GLTFLoaderState || (exports.GLTFLoaderState = {}));
  3157. /**
  3158. * File loader for loading glTF files into a scene.
  3159. */
  3160. var GLTFFileLoader = /** @class */ (function () {
  3161. function GLTFFileLoader() {
  3162. // --------------
  3163. // Common options
  3164. // --------------
  3165. /**
  3166. * Raised when the asset has been parsed
  3167. */
  3168. this.onParsedObservable = new babylonjs_1.Observable();
  3169. // ----------
  3170. // V2 options
  3171. // ----------
  3172. /**
  3173. * The coordinate system mode. Defaults to AUTO.
  3174. */
  3175. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  3176. /**
  3177. * The animation start mode. Defaults to FIRST.
  3178. */
  3179. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  3180. /**
  3181. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  3182. */
  3183. this.compileMaterials = false;
  3184. /**
  3185. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  3186. */
  3187. this.useClipPlane = false;
  3188. /**
  3189. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  3190. */
  3191. this.compileShadowGenerators = false;
  3192. /**
  3193. * Defines if the Alpha blended materials are only applied as coverage.
  3194. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  3195. * If true, no extra effects are applied to transparent pixels.
  3196. */
  3197. this.transparencyAsCoverage = false;
  3198. /**
  3199. * Function called before loading a url referenced by the asset.
  3200. */
  3201. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  3202. /**
  3203. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  3204. */
  3205. this.onMeshLoadedObservable = new babylonjs_1.Observable();
  3206. /**
  3207. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  3208. */
  3209. this.onTextureLoadedObservable = new babylonjs_1.Observable();
  3210. /**
  3211. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  3212. */
  3213. this.onMaterialLoadedObservable = new babylonjs_1.Observable();
  3214. /**
  3215. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  3216. */
  3217. this.onCameraLoadedObservable = new babylonjs_1.Observable();
  3218. /**
  3219. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  3220. * For assets with LODs, raised when all of the LODs are complete.
  3221. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  3222. */
  3223. this.onCompleteObservable = new babylonjs_1.Observable();
  3224. /**
  3225. * Observable raised when an error occurs.
  3226. */
  3227. this.onErrorObservable = new babylonjs_1.Observable();
  3228. /**
  3229. * Observable raised after the loader is disposed.
  3230. */
  3231. this.onDisposeObservable = new babylonjs_1.Observable();
  3232. /**
  3233. * Observable raised after a loader extension is created.
  3234. * Set additional options for a loader extension in this event.
  3235. */
  3236. this.onExtensionLoadedObservable = new babylonjs_1.Observable();
  3237. /**
  3238. * Defines if the loader should validate the asset.
  3239. */
  3240. this.validate = false;
  3241. /**
  3242. * Observable raised after validation when validate is set to true. The event data is the result of the validation.
  3243. */
  3244. this.onValidatedObservable = new babylonjs_1.Observable();
  3245. this._loader = null;
  3246. /**
  3247. * Name of the loader ("gltf")
  3248. */
  3249. this.name = "gltf";
  3250. /**
  3251. * Supported file extensions of the loader (.gltf, .glb)
  3252. */
  3253. this.extensions = {
  3254. ".gltf": { isBinary: false },
  3255. ".glb": { isBinary: true }
  3256. };
  3257. this._logIndentLevel = 0;
  3258. this._loggingEnabled = false;
  3259. /** @hidden */
  3260. this._log = this._logDisabled;
  3261. this._capturePerformanceCounters = false;
  3262. /** @hidden */
  3263. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  3264. /** @hidden */
  3265. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  3266. }
  3267. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  3268. /**
  3269. * Raised when the asset has been parsed
  3270. */
  3271. set: function (callback) {
  3272. if (this._onParsedObserver) {
  3273. this.onParsedObservable.remove(this._onParsedObserver);
  3274. }
  3275. this._onParsedObserver = this.onParsedObservable.add(callback);
  3276. },
  3277. enumerable: true,
  3278. configurable: true
  3279. });
  3280. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  3281. /**
  3282. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  3283. */
  3284. set: function (callback) {
  3285. if (this._onMeshLoadedObserver) {
  3286. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  3287. }
  3288. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  3289. },
  3290. enumerable: true,
  3291. configurable: true
  3292. });
  3293. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  3294. /**
  3295. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  3296. */
  3297. set: function (callback) {
  3298. if (this._onTextureLoadedObserver) {
  3299. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  3300. }
  3301. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  3302. },
  3303. enumerable: true,
  3304. configurable: true
  3305. });
  3306. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  3307. /**
  3308. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  3309. */
  3310. set: function (callback) {
  3311. if (this._onMaterialLoadedObserver) {
  3312. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  3313. }
  3314. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  3315. },
  3316. enumerable: true,
  3317. configurable: true
  3318. });
  3319. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  3320. /**
  3321. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  3322. */
  3323. set: function (callback) {
  3324. if (this._onCameraLoadedObserver) {
  3325. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  3326. }
  3327. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  3328. },
  3329. enumerable: true,
  3330. configurable: true
  3331. });
  3332. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  3333. /**
  3334. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  3335. * For assets with LODs, raised when all of the LODs are complete.
  3336. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  3337. */
  3338. set: function (callback) {
  3339. if (this._onCompleteObserver) {
  3340. this.onCompleteObservable.remove(this._onCompleteObserver);
  3341. }
  3342. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  3343. },
  3344. enumerable: true,
  3345. configurable: true
  3346. });
  3347. Object.defineProperty(GLTFFileLoader.prototype, "onError", {
  3348. /**
  3349. * Callback raised when an error occurs.
  3350. */
  3351. set: function (callback) {
  3352. if (this._onErrorObserver) {
  3353. this.onErrorObservable.remove(this._onErrorObserver);
  3354. }
  3355. this._onErrorObserver = this.onErrorObservable.add(callback);
  3356. },
  3357. enumerable: true,
  3358. configurable: true
  3359. });
  3360. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  3361. /**
  3362. * Callback raised after the loader is disposed.
  3363. */
  3364. set: function (callback) {
  3365. if (this._onDisposeObserver) {
  3366. this.onDisposeObservable.remove(this._onDisposeObserver);
  3367. }
  3368. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  3369. },
  3370. enumerable: true,
  3371. configurable: true
  3372. });
  3373. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  3374. /**
  3375. * Callback raised after a loader extension is created.
  3376. */
  3377. set: function (callback) {
  3378. if (this._onExtensionLoadedObserver) {
  3379. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  3380. }
  3381. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  3382. },
  3383. enumerable: true,
  3384. configurable: true
  3385. });
  3386. Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", {
  3387. /**
  3388. * Defines if the loader logging is enabled.
  3389. */
  3390. get: function () {
  3391. return this._loggingEnabled;
  3392. },
  3393. set: function (value) {
  3394. if (this._loggingEnabled === value) {
  3395. return;
  3396. }
  3397. this._loggingEnabled = value;
  3398. if (this._loggingEnabled) {
  3399. this._log = this._logEnabled;
  3400. }
  3401. else {
  3402. this._log = this._logDisabled;
  3403. }
  3404. },
  3405. enumerable: true,
  3406. configurable: true
  3407. });
  3408. Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", {
  3409. /**
  3410. * Defines if the loader should capture performance counters.
  3411. */
  3412. get: function () {
  3413. return this._capturePerformanceCounters;
  3414. },
  3415. set: function (value) {
  3416. if (this._capturePerformanceCounters === value) {
  3417. return;
  3418. }
  3419. this._capturePerformanceCounters = value;
  3420. if (this._capturePerformanceCounters) {
  3421. this._startPerformanceCounter = this._startPerformanceCounterEnabled;
  3422. this._endPerformanceCounter = this._endPerformanceCounterEnabled;
  3423. }
  3424. else {
  3425. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  3426. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  3427. }
  3428. },
  3429. enumerable: true,
  3430. configurable: true
  3431. });
  3432. Object.defineProperty(GLTFFileLoader.prototype, "onValidated", {
  3433. /**
  3434. * Callback raised after a loader extension is created.
  3435. */
  3436. set: function (callback) {
  3437. if (this._onValidatedObserver) {
  3438. this.onValidatedObservable.remove(this._onValidatedObserver);
  3439. }
  3440. this._onValidatedObserver = this.onValidatedObservable.add(callback);
  3441. },
  3442. enumerable: true,
  3443. configurable: true
  3444. });
  3445. /**
  3446. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  3447. */
  3448. GLTFFileLoader.prototype.dispose = function () {
  3449. if (this._loader) {
  3450. this._loader.dispose();
  3451. this._loader = null;
  3452. }
  3453. this._clear();
  3454. this.onDisposeObservable.notifyObservers(undefined);
  3455. this.onDisposeObservable.clear();
  3456. };
  3457. /** @hidden */
  3458. GLTFFileLoader.prototype._clear = function () {
  3459. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  3460. this.onMeshLoadedObservable.clear();
  3461. this.onTextureLoadedObservable.clear();
  3462. this.onMaterialLoadedObservable.clear();
  3463. this.onCameraLoadedObservable.clear();
  3464. this.onCompleteObservable.clear();
  3465. this.onExtensionLoadedObservable.clear();
  3466. };
  3467. /**
  3468. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  3469. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  3470. * @param scene the scene the meshes should be added to
  3471. * @param data the glTF data to load
  3472. * @param rootUrl root url to load from
  3473. * @param onProgress event that fires when loading progress has occured
  3474. * @param fileName Defines the name of the file to load
  3475. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  3476. */
  3477. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  3478. var _this = this;
  3479. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  3480. _this._log("Loading " + (fileName || ""));
  3481. _this._loader = _this._getLoader(loaderData);
  3482. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress, fileName);
  3483. });
  3484. };
  3485. /**
  3486. * Imports all objects from the loaded glTF data and adds them to the scene
  3487. * @param scene the scene the objects should be added to
  3488. * @param data the glTF data to load
  3489. * @param rootUrl root url to load from
  3490. * @param onProgress event that fires when loading progress has occured
  3491. * @param fileName Defines the name of the file to load
  3492. * @returns a promise which completes when objects have been loaded to the scene
  3493. */
  3494. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  3495. var _this = this;
  3496. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  3497. _this._log("Loading " + (fileName || ""));
  3498. _this._loader = _this._getLoader(loaderData);
  3499. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress, fileName);
  3500. });
  3501. };
  3502. /**
  3503. * Load into an asset container.
  3504. * @param scene The scene to load into
  3505. * @param data The data to import
  3506. * @param rootUrl The root url for scene and resources
  3507. * @param onProgress The callback when the load progresses
  3508. * @param fileName Defines the name of the file to load
  3509. * @returns The loaded asset container
  3510. */
  3511. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress, fileName) {
  3512. var _this = this;
  3513. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  3514. _this._log("Loading " + (fileName || ""));
  3515. _this._loader = _this._getLoader(loaderData);
  3516. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress, fileName).then(function (result) {
  3517. var container = new babylonjs_1.AssetContainer(scene);
  3518. Array.prototype.push.apply(container.meshes, result.meshes);
  3519. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  3520. Array.prototype.push.apply(container.skeletons, result.skeletons);
  3521. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  3522. container.removeAllFromScene();
  3523. return container;
  3524. });
  3525. });
  3526. };
  3527. /**
  3528. * If the data string can be loaded directly.
  3529. * @param data string contianing the file data
  3530. * @returns if the data can be loaded directly
  3531. */
  3532. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  3533. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  3534. };
  3535. /**
  3536. * Instantiates a glTF file loader plugin.
  3537. * @returns the created plugin
  3538. */
  3539. GLTFFileLoader.prototype.createPlugin = function () {
  3540. return new GLTFFileLoader();
  3541. };
  3542. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  3543. /**
  3544. * The loader state or null if the loader is not active.
  3545. */
  3546. get: function () {
  3547. return this._loader ? this._loader.state : null;
  3548. },
  3549. enumerable: true,
  3550. configurable: true
  3551. });
  3552. /**
  3553. * Returns a promise that resolves when the asset is completely loaded.
  3554. * @returns a promise that resolves when the asset is completely loaded.
  3555. */
  3556. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  3557. var _this = this;
  3558. return new Promise(function (resolve, reject) {
  3559. _this.onCompleteObservable.addOnce(function () {
  3560. resolve();
  3561. });
  3562. _this.onErrorObservable.addOnce(function (reason) {
  3563. reject(reason);
  3564. });
  3565. });
  3566. };
  3567. GLTFFileLoader.prototype._parseAsync = function (scene, data, rootUrl, fileName) {
  3568. var _this = this;
  3569. return Promise.resolve().then(function () {
  3570. var unpacked = (data instanceof ArrayBuffer) ? _this._unpackBinary(data) : { json: data, bin: null };
  3571. return _this._validateAsync(scene, unpacked.json, rootUrl, fileName).then(function () {
  3572. _this._startPerformanceCounter("Parse JSON");
  3573. _this._log("JSON length: " + unpacked.json.length);
  3574. var loaderData = {
  3575. json: JSON.parse(unpacked.json),
  3576. bin: unpacked.bin
  3577. };
  3578. _this._endPerformanceCounter("Parse JSON");
  3579. _this.onParsedObservable.notifyObservers(loaderData);
  3580. _this.onParsedObservable.clear();
  3581. return loaderData;
  3582. });
  3583. });
  3584. };
  3585. GLTFFileLoader.prototype._validateAsync = function (scene, json, rootUrl, fileName) {
  3586. var _this = this;
  3587. if (!this.validate || typeof GLTFValidator === "undefined") {
  3588. return Promise.resolve();
  3589. }
  3590. this._startPerformanceCounter("Validate JSON");
  3591. var options = {
  3592. externalResourceFunction: function (uri) {
  3593. return _this.preprocessUrlAsync(rootUrl + uri)
  3594. .then(function (url) { return scene._loadFileAsync(url, true, true); })
  3595. .then(function (data) { return new Uint8Array(data); });
  3596. }
  3597. };
  3598. if (fileName && fileName.substr(0, 5) !== "data:") {
  3599. options.uri = (rootUrl === "file:" ? fileName : "" + rootUrl + fileName);
  3600. }
  3601. return GLTFValidator.validateString(json, options).then(function (result) {
  3602. _this._endPerformanceCounter("Validate JSON");
  3603. _this.onValidatedObservable.notifyObservers(result);
  3604. _this.onValidatedObservable.clear();
  3605. }, function (reason) {
  3606. _this._endPerformanceCounter("Validate JSON");
  3607. babylonjs_1.Tools.Warn("Failed to validate: " + reason);
  3608. _this.onValidatedObservable.clear();
  3609. });
  3610. };
  3611. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  3612. var asset = loaderData.json.asset || {};
  3613. this._log("Asset version: " + asset.version);
  3614. asset.minVersion && this._log("Asset minimum version: " + asset.minVersion);
  3615. asset.generator && this._log("Asset generator: " + asset.generator);
  3616. var version = GLTFFileLoader._parseVersion(asset.version);
  3617. if (!version) {
  3618. throw new Error("Invalid version: " + asset.version);
  3619. }
  3620. if (asset.minVersion !== undefined) {
  3621. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  3622. if (!minVersion) {
  3623. throw new Error("Invalid minimum version: " + asset.minVersion);
  3624. }
  3625. if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
  3626. throw new Error("Incompatible minimum version: " + asset.minVersion);
  3627. }
  3628. }
  3629. var createLoaders = {
  3630. 1: GLTFFileLoader._CreateGLTF1Loader,
  3631. 2: GLTFFileLoader._CreateGLTF2Loader
  3632. };
  3633. var createLoader = createLoaders[version.major];
  3634. if (!createLoader) {
  3635. throw new Error("Unsupported version: " + asset.version);
  3636. }
  3637. return createLoader(this);
  3638. };
  3639. GLTFFileLoader.prototype._unpackBinary = function (data) {
  3640. this._startPerformanceCounter("Unpack binary");
  3641. this._log("Binary length: " + data.byteLength);
  3642. var Binary = {
  3643. Magic: 0x46546C67
  3644. };
  3645. var binaryReader = new BinaryReader(data);
  3646. var magic = binaryReader.readUint32();
  3647. if (magic !== Binary.Magic) {
  3648. throw new Error("Unexpected magic: " + magic);
  3649. }
  3650. var version = binaryReader.readUint32();
  3651. if (this.loggingEnabled) {
  3652. this._log("Binary version: " + version);
  3653. }
  3654. var unpacked;
  3655. switch (version) {
  3656. case 1: {
  3657. unpacked = this._unpackBinaryV1(binaryReader);
  3658. break;
  3659. }
  3660. case 2: {
  3661. unpacked = this._unpackBinaryV2(binaryReader);
  3662. break;
  3663. }
  3664. default: {
  3665. throw new Error("Unsupported version: " + version);
  3666. }
  3667. }
  3668. this._endPerformanceCounter("Unpack binary");
  3669. return unpacked;
  3670. };
  3671. GLTFFileLoader.prototype._unpackBinaryV1 = function (binaryReader) {
  3672. var ContentFormat = {
  3673. JSON: 0
  3674. };
  3675. var length = binaryReader.readUint32();
  3676. if (length != binaryReader.getLength()) {
  3677. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  3678. }
  3679. var contentLength = binaryReader.readUint32();
  3680. var contentFormat = binaryReader.readUint32();
  3681. var content;
  3682. switch (contentFormat) {
  3683. case ContentFormat.JSON: {
  3684. content = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength));
  3685. break;
  3686. }
  3687. default: {
  3688. throw new Error("Unexpected content format: " + contentFormat);
  3689. }
  3690. }
  3691. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  3692. var body = binaryReader.readUint8Array(bytesRemaining);
  3693. return {
  3694. json: content,
  3695. bin: body
  3696. };
  3697. };
  3698. GLTFFileLoader.prototype._unpackBinaryV2 = function (binaryReader) {
  3699. var ChunkFormat = {
  3700. JSON: 0x4E4F534A,
  3701. BIN: 0x004E4942
  3702. };
  3703. var length = binaryReader.readUint32();
  3704. if (length !== binaryReader.getLength()) {
  3705. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  3706. }
  3707. // JSON chunk
  3708. var chunkLength = binaryReader.readUint32();
  3709. var chunkFormat = binaryReader.readUint32();
  3710. if (chunkFormat !== ChunkFormat.JSON) {
  3711. throw new Error("First chunk format is not JSON");
  3712. }
  3713. var json = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength));
  3714. // Look for BIN chunk
  3715. var bin = null;
  3716. while (binaryReader.getPosition() < binaryReader.getLength()) {
  3717. var chunkLength_1 = binaryReader.readUint32();
  3718. var chunkFormat_1 = binaryReader.readUint32();
  3719. switch (chunkFormat_1) {
  3720. case ChunkFormat.JSON: {
  3721. throw new Error("Unexpected JSON chunk");
  3722. }
  3723. case ChunkFormat.BIN: {
  3724. bin = binaryReader.readUint8Array(chunkLength_1);
  3725. break;
  3726. }
  3727. default: {
  3728. // ignore unrecognized chunkFormat
  3729. binaryReader.skipBytes(chunkLength_1);
  3730. break;
  3731. }
  3732. }
  3733. }
  3734. return {
  3735. json: json,
  3736. bin: bin
  3737. };
  3738. };
  3739. GLTFFileLoader._parseVersion = function (version) {
  3740. if (version === "1.0" || version === "1.0.1") {
  3741. return {
  3742. major: 1,
  3743. minor: 0
  3744. };
  3745. }
  3746. var match = (version + "").match(/^(\d+)\.(\d+)/);
  3747. if (!match) {
  3748. return null;
  3749. }
  3750. return {
  3751. major: parseInt(match[1]),
  3752. minor: parseInt(match[2])
  3753. };
  3754. };
  3755. GLTFFileLoader._compareVersion = function (a, b) {
  3756. if (a.major > b.major) {
  3757. return 1;
  3758. }
  3759. if (a.major < b.major) {
  3760. return -1;
  3761. }
  3762. if (a.minor > b.minor) {
  3763. return 1;
  3764. }
  3765. if (a.minor < b.minor) {
  3766. return -1;
  3767. }
  3768. return 0;
  3769. };
  3770. GLTFFileLoader._decodeBufferToText = function (buffer) {
  3771. var result = "";
  3772. var length = buffer.byteLength;
  3773. for (var i = 0; i < length; i++) {
  3774. result += String.fromCharCode(buffer[i]);
  3775. }
  3776. return result;
  3777. };
  3778. /** @hidden */
  3779. GLTFFileLoader.prototype._logOpen = function (message) {
  3780. this._log(message);
  3781. this._logIndentLevel++;
  3782. };
  3783. /** @hidden */
  3784. GLTFFileLoader.prototype._logClose = function () {
  3785. --this._logIndentLevel;
  3786. };
  3787. GLTFFileLoader.prototype._logEnabled = function (message) {
  3788. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  3789. babylonjs_1.Tools.Log("" + spaces + message);
  3790. };
  3791. GLTFFileLoader.prototype._logDisabled = function (message) {
  3792. };
  3793. GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
  3794. babylonjs_1.Tools.StartPerformanceCounter(counterName);
  3795. };
  3796. GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
  3797. };
  3798. GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
  3799. babylonjs_1.Tools.EndPerformanceCounter(counterName);
  3800. };
  3801. GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
  3802. };
  3803. // ----------
  3804. // V1 options
  3805. // ----------
  3806. /**
  3807. * Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders.
  3808. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  3809. * Defaults to true.
  3810. * @hidden
  3811. */
  3812. GLTFFileLoader.IncrementalLoading = true;
  3813. /**
  3814. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  3815. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  3816. * @hidden
  3817. */
  3818. GLTFFileLoader.HomogeneousCoordinates = false;
  3819. GLTFFileLoader._logSpaces = " ";
  3820. return GLTFFileLoader;
  3821. }());
  3822. exports.GLTFFileLoader = GLTFFileLoader;
  3823. var BinaryReader = /** @class */ (function () {
  3824. function BinaryReader(arrayBuffer) {
  3825. this._arrayBuffer = arrayBuffer;
  3826. this._dataView = new DataView(arrayBuffer);
  3827. this._byteOffset = 0;
  3828. }
  3829. BinaryReader.prototype.getPosition = function () {
  3830. return this._byteOffset;
  3831. };
  3832. BinaryReader.prototype.getLength = function () {
  3833. return this._arrayBuffer.byteLength;
  3834. };
  3835. BinaryReader.prototype.readUint32 = function () {
  3836. var value = this._dataView.getUint32(this._byteOffset, true);
  3837. this._byteOffset += 4;
  3838. return value;
  3839. };
  3840. BinaryReader.prototype.readUint8Array = function (length) {
  3841. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  3842. this._byteOffset += length;
  3843. return value;
  3844. };
  3845. BinaryReader.prototype.skipBytes = function (length) {
  3846. this._byteOffset += length;
  3847. };
  3848. return BinaryReader;
  3849. }());
  3850. if (babylonjs_1.SceneLoader) {
  3851. babylonjs_1.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  3852. }
  3853. /***/ }),
  3854. /***/ "babylonjs":
  3855. /*!****************************************************************************************************!*\
  3856. !*** external {"root":"BABYLON","commonjs":"babylonjs","commonjs2":"babylonjs","amd":"babylonjs"} ***!
  3857. \****************************************************************************************************/
  3858. /*! no static exports found */
  3859. /***/ (function(module, exports) {
  3860. module.exports = __WEBPACK_EXTERNAL_MODULE_babylonjs__;
  3861. /***/ })
  3862. /******/ });
  3863. });
  3864. //# sourceMappingURL=babylon.glTF2FileLoader.js.map