babylon.glTF1FileLoader.js 138 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267
  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-glTF1FileLoader.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-glTF.ts":
  122. /*!*******************************!*\
  123. !*** ./legacy/legacy-glTF.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. /**
  135. * This is the entry point for the UMD module.
  136. * The entry point for a future ESM package should be index.ts
  137. */
  138. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined);
  139. if (typeof globalObject !== "undefined") {
  140. globalObject.BABYLON = globalObject.BABYLON || {};
  141. for (var key in FileLoader) {
  142. globalObject.BABYLON[key] = FileLoader[key];
  143. }
  144. }
  145. __export(__webpack_require__(/*! ../src/glTF/glTFFileLoader */ "./src/glTF/glTFFileLoader.ts"));
  146. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/global.js */ "../node_modules/webpack/buildin/global.js")))
  147. /***/ }),
  148. /***/ "./legacy/legacy-glTF1.ts":
  149. /*!********************************!*\
  150. !*** ./legacy/legacy-glTF1.ts ***!
  151. \********************************/
  152. /*! no static exports found */
  153. /***/ (function(module, exports, __webpack_require__) {
  154. "use strict";
  155. /* WEBPACK VAR INJECTION */(function(global) {
  156. Object.defineProperty(exports, "__esModule", { value: true });
  157. var GLTF1 = __webpack_require__(/*! ../src/glTF/1.0 */ "./src/glTF/1.0/index.ts");
  158. exports.GLTF1 = GLTF1;
  159. /**
  160. * This is the entry point for the UMD module.
  161. * The entry point for a future ESM package should be index.ts
  162. */
  163. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined);
  164. if (typeof globalObject !== "undefined") {
  165. globalObject.BABYLON = globalObject.BABYLON || {};
  166. globalObject.BABYLON.GLTF1 = globalObject.BABYLON.GLTF1 || {};
  167. for (var key in GLTF1) {
  168. globalObject.BABYLON.GLTF1[key] = GLTF1[key];
  169. }
  170. }
  171. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/global.js */ "../node_modules/webpack/buildin/global.js")))
  172. /***/ }),
  173. /***/ "./legacy/legacy-glTF1FileLoader.ts":
  174. /*!******************************************!*\
  175. !*** ./legacy/legacy-glTF1FileLoader.ts ***!
  176. \******************************************/
  177. /*! no static exports found */
  178. /***/ (function(module, exports, __webpack_require__) {
  179. "use strict";
  180. function __export(m) {
  181. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  182. }
  183. Object.defineProperty(exports, "__esModule", { value: true });
  184. __export(__webpack_require__(/*! ./legacy-glTF */ "./legacy/legacy-glTF.ts"));
  185. __export(__webpack_require__(/*! ./legacy-glTF1 */ "./legacy/legacy-glTF1.ts"));
  186. /***/ }),
  187. /***/ "./src/glTF/1.0/glTFBinaryExtension.ts":
  188. /*!*********************************************!*\
  189. !*** ./src/glTF/1.0/glTFBinaryExtension.ts ***!
  190. \*********************************************/
  191. /*! no static exports found */
  192. /***/ (function(module, exports, __webpack_require__) {
  193. "use strict";
  194. var __extends = (this && this.__extends) || (function () {
  195. var extendStatics = function (d, b) {
  196. extendStatics = Object.setPrototypeOf ||
  197. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  198. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  199. return extendStatics(d, b);
  200. }
  201. return function (d, b) {
  202. extendStatics(d, b);
  203. function __() { this.constructor = d; }
  204. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  205. };
  206. })();
  207. Object.defineProperty(exports, "__esModule", { value: true });
  208. var glTFLoaderExtension_1 = __webpack_require__(/*! ./glTFLoaderExtension */ "./src/glTF/1.0/glTFLoaderExtension.ts");
  209. var glTFLoaderUtils_1 = __webpack_require__(/*! ./glTFLoaderUtils */ "./src/glTF/1.0/glTFLoaderUtils.ts");
  210. var glTFLoaderInterfaces_1 = __webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/1.0/glTFLoaderInterfaces.ts");
  211. var glTFLoader_1 = __webpack_require__(/*! ./glTFLoader */ "./src/glTF/1.0/glTFLoader.ts");
  212. var BinaryExtensionBufferName = "binary_glTF";
  213. /** @hidden */
  214. var GLTFBinaryExtension = /** @class */ (function (_super) {
  215. __extends(GLTFBinaryExtension, _super);
  216. function GLTFBinaryExtension() {
  217. return _super.call(this, "KHR_binary_glTF") || this;
  218. }
  219. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  220. var extensionsUsed = data.json.extensionsUsed;
  221. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  222. return false;
  223. }
  224. this._bin = data.bin;
  225. onSuccess(glTFLoader_1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  226. return true;
  227. };
  228. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  229. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  230. return false;
  231. }
  232. if (id !== BinaryExtensionBufferName) {
  233. return false;
  234. }
  235. onSuccess(this._bin);
  236. return true;
  237. };
  238. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  239. var texture = gltfRuntime.textures[id];
  240. var source = gltfRuntime.images[texture.source];
  241. if (!source.extensions || !(this.name in source.extensions)) {
  242. return false;
  243. }
  244. var sourceExt = source.extensions[this.name];
  245. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  246. var buffer = glTFLoaderUtils_1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, glTFLoaderInterfaces_1.EComponentType.UNSIGNED_BYTE);
  247. onSuccess(buffer);
  248. return true;
  249. };
  250. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  251. var shader = gltfRuntime.shaders[id];
  252. if (!shader.extensions || !(this.name in shader.extensions)) {
  253. return false;
  254. }
  255. var binaryExtensionShader = shader.extensions[this.name];
  256. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  257. var shaderBytes = glTFLoaderUtils_1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, glTFLoaderInterfaces_1.EComponentType.UNSIGNED_BYTE);
  258. setTimeout(function () {
  259. var shaderString = glTFLoaderUtils_1.GLTFUtils.DecodeBufferToText(shaderBytes);
  260. onSuccess(shaderString);
  261. });
  262. return true;
  263. };
  264. return GLTFBinaryExtension;
  265. }(glTFLoaderExtension_1.GLTFLoaderExtension));
  266. exports.GLTFBinaryExtension = GLTFBinaryExtension;
  267. glTFLoader_1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  268. /***/ }),
  269. /***/ "./src/glTF/1.0/glTFLoader.ts":
  270. /*!************************************!*\
  271. !*** ./src/glTF/1.0/glTFLoader.ts ***!
  272. \************************************/
  273. /*! no static exports found */
  274. /***/ (function(module, exports, __webpack_require__) {
  275. "use strict";
  276. Object.defineProperty(exports, "__esModule", { value: true });
  277. var glTFLoaderInterfaces_1 = __webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/1.0/glTFLoaderInterfaces.ts");
  278. var glTFLoaderUtils_1 = __webpack_require__(/*! ./glTFLoaderUtils */ "./src/glTF/1.0/glTFLoaderUtils.ts");
  279. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  280. var glTFFileLoader_1 = __webpack_require__(/*! ../glTFFileLoader */ "./src/glTF/glTFFileLoader.ts");
  281. var glTFLoaderExtension_1 = __webpack_require__(/*! ./glTFLoaderExtension */ "./src/glTF/1.0/glTFLoaderExtension.ts");
  282. /**
  283. * Tokenizer. Used for shaders compatibility
  284. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  285. */
  286. var ETokenType;
  287. (function (ETokenType) {
  288. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  289. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  290. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  291. })(ETokenType || (ETokenType = {}));
  292. var Tokenizer = /** @class */ (function () {
  293. function Tokenizer(toParse) {
  294. this._pos = 0;
  295. this.currentToken = ETokenType.UNKNOWN;
  296. this.currentIdentifier = "";
  297. this.currentString = "";
  298. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  299. this._toParse = toParse;
  300. this._maxPos = toParse.length;
  301. }
  302. Tokenizer.prototype.getNextToken = function () {
  303. if (this.isEnd()) {
  304. return ETokenType.END_OF_INPUT;
  305. }
  306. this.currentString = this.read();
  307. this.currentToken = ETokenType.UNKNOWN;
  308. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  309. this.currentToken = ETokenType.IDENTIFIER;
  310. this.currentIdentifier = this.currentString;
  311. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  312. this.currentIdentifier += this.currentString;
  313. this.forward();
  314. }
  315. }
  316. return this.currentToken;
  317. };
  318. Tokenizer.prototype.peek = function () {
  319. return this._toParse[this._pos];
  320. };
  321. Tokenizer.prototype.read = function () {
  322. return this._toParse[this._pos++];
  323. };
  324. Tokenizer.prototype.forward = function () {
  325. this._pos++;
  326. };
  327. Tokenizer.prototype.isEnd = function () {
  328. return this._pos >= this._maxPos;
  329. };
  330. return Tokenizer;
  331. }());
  332. /**
  333. * Values
  334. */
  335. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  336. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  337. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  338. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  339. /**
  340. * Parse
  341. */
  342. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  343. for (var buf in parsedBuffers) {
  344. var parsedBuffer = parsedBuffers[buf];
  345. gltfRuntime.buffers[buf] = parsedBuffer;
  346. gltfRuntime.buffersCount++;
  347. }
  348. };
  349. var parseShaders = function (parsedShaders, gltfRuntime) {
  350. for (var sha in parsedShaders) {
  351. var parsedShader = parsedShaders[sha];
  352. gltfRuntime.shaders[sha] = parsedShader;
  353. gltfRuntime.shaderscount++;
  354. }
  355. };
  356. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  357. for (var object in parsedObjects) {
  358. var parsedObject = parsedObjects[object];
  359. gltfRuntime[runtimeProperty][object] = parsedObject;
  360. }
  361. };
  362. /**
  363. * Utils
  364. */
  365. var normalizeUVs = function (buffer) {
  366. if (!buffer) {
  367. return;
  368. }
  369. for (var i = 0; i < buffer.length / 2; i++) {
  370. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  371. }
  372. };
  373. var getAttribute = function (attributeParameter) {
  374. if (attributeParameter.semantic === "NORMAL") {
  375. return "normal";
  376. }
  377. else if (attributeParameter.semantic === "POSITION") {
  378. return "position";
  379. }
  380. else if (attributeParameter.semantic === "JOINT") {
  381. return "matricesIndices";
  382. }
  383. else if (attributeParameter.semantic === "WEIGHT") {
  384. return "matricesWeights";
  385. }
  386. else if (attributeParameter.semantic === "COLOR") {
  387. return "color";
  388. }
  389. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  390. var channel = Number(attributeParameter.semantic.split("_")[1]);
  391. return "uv" + (channel === 0 ? "" : channel + 1);
  392. }
  393. return null;
  394. };
  395. /**
  396. * Loads and creates animations
  397. */
  398. var loadAnimations = function (gltfRuntime) {
  399. for (var anim in gltfRuntime.animations) {
  400. var animation = gltfRuntime.animations[anim];
  401. if (!animation.channels || !animation.samplers) {
  402. continue;
  403. }
  404. var lastAnimation = null;
  405. for (var i = 0; i < animation.channels.length; i++) {
  406. // Get parameters and load buffers
  407. var channel = animation.channels[i];
  408. var sampler = animation.samplers[channel.sampler];
  409. if (!sampler) {
  410. continue;
  411. }
  412. var inputData = null;
  413. var outputData = null;
  414. if (animation.parameters) {
  415. inputData = animation.parameters[sampler.input];
  416. outputData = animation.parameters[sampler.output];
  417. }
  418. else {
  419. inputData = sampler.input;
  420. outputData = sampler.output;
  421. }
  422. var bufferInput = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  423. var bufferOutput = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  424. var targetID = channel.target.id;
  425. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  426. if (targetNode === null) {
  427. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  428. }
  429. if (targetNode === null) {
  430. babylonjs_1.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  431. continue;
  432. }
  433. var isBone = targetNode instanceof babylonjs_1.Bone;
  434. // Get target path (position, rotation or scaling)
  435. var targetPath = channel.target.path;
  436. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  437. if (targetPathIndex !== -1) {
  438. targetPath = babylonAnimationPaths[targetPathIndex];
  439. }
  440. // Determine animation type
  441. var animationType = babylonjs_1.Animation.ANIMATIONTYPE_MATRIX;
  442. if (!isBone) {
  443. if (targetPath === "rotationQuaternion") {
  444. animationType = babylonjs_1.Animation.ANIMATIONTYPE_QUATERNION;
  445. targetNode.rotationQuaternion = new babylonjs_1.Quaternion();
  446. }
  447. else {
  448. animationType = babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3;
  449. }
  450. }
  451. // Create animation and key frames
  452. var babylonAnimation = null;
  453. var keys = [];
  454. var arrayOffset = 0;
  455. var modifyKey = false;
  456. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  457. babylonAnimation = lastAnimation;
  458. modifyKey = true;
  459. }
  460. if (!modifyKey) {
  461. babylonAnimation = new babylonjs_1.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, babylonjs_1.Animation.ANIMATIONLOOPMODE_CYCLE);
  462. }
  463. // For each frame
  464. for (var j = 0; j < bufferInput.length; j++) {
  465. var value = null;
  466. if (targetPath === "rotationQuaternion") { // VEC4
  467. value = babylonjs_1.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  468. arrayOffset += 4;
  469. }
  470. else { // Position and scaling are VEC3
  471. value = babylonjs_1.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  472. arrayOffset += 3;
  473. }
  474. if (isBone) {
  475. var bone = targetNode;
  476. var translation = babylonjs_1.Vector3.Zero();
  477. var rotationQuaternion = new babylonjs_1.Quaternion();
  478. var scaling = babylonjs_1.Vector3.Zero();
  479. // Warning on decompose
  480. var mat = bone.getBaseMatrix();
  481. if (modifyKey && lastAnimation) {
  482. mat = lastAnimation.getKeys()[j].value;
  483. }
  484. mat.decompose(scaling, rotationQuaternion, translation);
  485. if (targetPath === "position") {
  486. translation = value;
  487. }
  488. else if (targetPath === "rotationQuaternion") {
  489. rotationQuaternion = value;
  490. }
  491. else {
  492. scaling = value;
  493. }
  494. value = babylonjs_1.Matrix.Compose(scaling, rotationQuaternion, translation);
  495. }
  496. if (!modifyKey) {
  497. keys.push({
  498. frame: bufferInput[j],
  499. value: value
  500. });
  501. }
  502. else if (lastAnimation) {
  503. lastAnimation.getKeys()[j].value = value;
  504. }
  505. }
  506. // Finish
  507. if (!modifyKey && babylonAnimation) {
  508. babylonAnimation.setKeys(keys);
  509. targetNode.animations.push(babylonAnimation);
  510. }
  511. lastAnimation = babylonAnimation;
  512. gltfRuntime.scene.stopAnimation(targetNode);
  513. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  514. }
  515. }
  516. };
  517. /**
  518. * Returns the bones transformation matrix
  519. */
  520. var configureBoneTransformation = function (node) {
  521. var mat = null;
  522. if (node.translation || node.rotation || node.scale) {
  523. var scale = babylonjs_1.Vector3.FromArray(node.scale || [1, 1, 1]);
  524. var rotation = babylonjs_1.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  525. var position = babylonjs_1.Vector3.FromArray(node.translation || [0, 0, 0]);
  526. mat = babylonjs_1.Matrix.Compose(scale, rotation, position);
  527. }
  528. else {
  529. mat = babylonjs_1.Matrix.FromArray(node.matrix);
  530. }
  531. return mat;
  532. };
  533. /**
  534. * Returns the parent bone
  535. */
  536. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  537. // Try to find
  538. for (var i = 0; i < newSkeleton.bones.length; i++) {
  539. if (newSkeleton.bones[i].name === jointName) {
  540. return newSkeleton.bones[i];
  541. }
  542. }
  543. // Not found, search in gltf nodes
  544. var nodes = gltfRuntime.nodes;
  545. for (var nde in nodes) {
  546. var node = nodes[nde];
  547. if (!node.jointName) {
  548. continue;
  549. }
  550. var children = node.children;
  551. for (var i = 0; i < children.length; i++) {
  552. var child = gltfRuntime.nodes[children[i]];
  553. if (!child.jointName) {
  554. continue;
  555. }
  556. if (child.jointName === jointName) {
  557. var mat = configureBoneTransformation(node);
  558. var bone = new babylonjs_1.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  559. bone.id = nde;
  560. return bone;
  561. }
  562. }
  563. }
  564. return null;
  565. };
  566. /**
  567. * Returns the appropriate root node
  568. */
  569. var getNodeToRoot = function (nodesToRoot, id) {
  570. for (var i = 0; i < nodesToRoot.length; i++) {
  571. var nodeToRoot = nodesToRoot[i];
  572. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  573. var child = nodeToRoot.node.children[j];
  574. if (child === id) {
  575. return nodeToRoot.bone;
  576. }
  577. }
  578. }
  579. return null;
  580. };
  581. /**
  582. * Returns the node with the joint name
  583. */
  584. var getJointNode = function (gltfRuntime, jointName) {
  585. var nodes = gltfRuntime.nodes;
  586. var node = nodes[jointName];
  587. if (node) {
  588. return {
  589. node: node,
  590. id: jointName
  591. };
  592. }
  593. for (var nde in nodes) {
  594. node = nodes[nde];
  595. if (node.jointName === jointName) {
  596. return {
  597. node: node,
  598. id: nde
  599. };
  600. }
  601. }
  602. return null;
  603. };
  604. /**
  605. * Checks if a nodes is in joints
  606. */
  607. var nodeIsInJoints = function (skins, id) {
  608. for (var i = 0; i < skins.jointNames.length; i++) {
  609. if (skins.jointNames[i] === id) {
  610. return true;
  611. }
  612. }
  613. return false;
  614. };
  615. /**
  616. * Fills the nodes to root for bones and builds hierarchy
  617. */
  618. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  619. // Creates nodes for root
  620. for (var nde in gltfRuntime.nodes) {
  621. var node = gltfRuntime.nodes[nde];
  622. var id = nde;
  623. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  624. continue;
  625. }
  626. // Create node to root bone
  627. var mat = configureBoneTransformation(node);
  628. var bone = new babylonjs_1.Bone(node.name || "", newSkeleton, null, mat);
  629. bone.id = id;
  630. nodesToRoot.push({ bone: bone, node: node, id: id });
  631. }
  632. // Parenting
  633. for (var i = 0; i < nodesToRoot.length; i++) {
  634. var nodeToRoot = nodesToRoot[i];
  635. var children = nodeToRoot.node.children;
  636. for (var j = 0; j < children.length; j++) {
  637. var child = null;
  638. for (var k = 0; k < nodesToRoot.length; k++) {
  639. if (nodesToRoot[k].id === children[j]) {
  640. child = nodesToRoot[k];
  641. break;
  642. }
  643. }
  644. if (child) {
  645. child.bone._parent = nodeToRoot.bone;
  646. nodeToRoot.bone.children.push(child.bone);
  647. }
  648. }
  649. }
  650. };
  651. /**
  652. * Imports a skeleton
  653. */
  654. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  655. if (!newSkeleton) {
  656. newSkeleton = new babylonjs_1.Skeleton(skins.name || "", "", gltfRuntime.scene);
  657. }
  658. if (!skins.babylonSkeleton) {
  659. return newSkeleton;
  660. }
  661. // Find the root bones
  662. var nodesToRoot = [];
  663. var nodesToRootToAdd = [];
  664. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  665. newSkeleton.bones = [];
  666. // Joints
  667. for (var i = 0; i < skins.jointNames.length; i++) {
  668. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  669. if (!jointNode) {
  670. continue;
  671. }
  672. var node = jointNode.node;
  673. if (!node) {
  674. babylonjs_1.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  675. continue;
  676. }
  677. var id = jointNode.id;
  678. // Optimize, if the bone already exists...
  679. var existingBone = gltfRuntime.scene.getBoneByID(id);
  680. if (existingBone) {
  681. newSkeleton.bones.push(existingBone);
  682. continue;
  683. }
  684. // Search for parent bone
  685. var foundBone = false;
  686. var parentBone = null;
  687. for (var j = 0; j < i; j++) {
  688. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  689. if (!jointNode_1) {
  690. continue;
  691. }
  692. var joint = jointNode_1.node;
  693. if (!joint) {
  694. babylonjs_1.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  695. continue;
  696. }
  697. var children = joint.children;
  698. if (!children) {
  699. continue;
  700. }
  701. foundBone = false;
  702. for (var k = 0; k < children.length; k++) {
  703. if (children[k] === id) {
  704. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  705. foundBone = true;
  706. break;
  707. }
  708. }
  709. if (foundBone) {
  710. break;
  711. }
  712. }
  713. // Create bone
  714. var mat = configureBoneTransformation(node);
  715. if (!parentBone && nodesToRoot.length > 0) {
  716. parentBone = getNodeToRoot(nodesToRoot, id);
  717. if (parentBone) {
  718. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  719. nodesToRootToAdd.push(parentBone);
  720. }
  721. }
  722. }
  723. var bone = new babylonjs_1.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  724. bone.id = id;
  725. }
  726. // Polish
  727. var bones = newSkeleton.bones;
  728. newSkeleton.bones = [];
  729. for (var i = 0; i < skins.jointNames.length; i++) {
  730. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  731. if (!jointNode) {
  732. continue;
  733. }
  734. for (var j = 0; j < bones.length; j++) {
  735. if (bones[j].id === jointNode.id) {
  736. newSkeleton.bones.push(bones[j]);
  737. break;
  738. }
  739. }
  740. }
  741. newSkeleton.prepare();
  742. // Finish
  743. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  744. newSkeleton.bones.push(nodesToRootToAdd[i]);
  745. }
  746. return newSkeleton;
  747. };
  748. /**
  749. * Imports a mesh and its geometries
  750. */
  751. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  752. if (!newMesh) {
  753. newMesh = new babylonjs_1.Mesh(node.name || "", gltfRuntime.scene);
  754. newMesh.id = id;
  755. }
  756. if (!node.babylonNode) {
  757. return newMesh;
  758. }
  759. var subMaterials = [];
  760. var vertexData = null;
  761. var verticesStarts = new Array();
  762. var verticesCounts = new Array();
  763. var indexStarts = new Array();
  764. var indexCounts = new Array();
  765. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  766. var meshID = meshes[meshIndex];
  767. var mesh = gltfRuntime.meshes[meshID];
  768. if (!mesh) {
  769. continue;
  770. }
  771. // Positions, normals and UVs
  772. for (var i = 0; i < mesh.primitives.length; i++) {
  773. // Temporary vertex data
  774. var tempVertexData = new babylonjs_1.VertexData();
  775. var primitive = mesh.primitives[i];
  776. if (primitive.mode !== 4) {
  777. // continue;
  778. }
  779. var attributes = primitive.attributes;
  780. var accessor = null;
  781. var buffer = null;
  782. // Set positions, normal and uvs
  783. for (var semantic in attributes) {
  784. // Link accessor and buffer view
  785. accessor = gltfRuntime.accessors[attributes[semantic]];
  786. buffer = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  787. if (semantic === "NORMAL") {
  788. tempVertexData.normals = new Float32Array(buffer.length);
  789. tempVertexData.normals.set(buffer);
  790. }
  791. else if (semantic === "POSITION") {
  792. if (glTFFileLoader_1.GLTFFileLoader.HomogeneousCoordinates) {
  793. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  794. for (var j = 0; j < buffer.length; j += 4) {
  795. tempVertexData.positions[j] = buffer[j];
  796. tempVertexData.positions[j + 1] = buffer[j + 1];
  797. tempVertexData.positions[j + 2] = buffer[j + 2];
  798. }
  799. }
  800. else {
  801. tempVertexData.positions = new Float32Array(buffer.length);
  802. tempVertexData.positions.set(buffer);
  803. }
  804. verticesCounts.push(tempVertexData.positions.length);
  805. }
  806. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  807. var channel = Number(semantic.split("_")[1]);
  808. var uvKind = babylonjs_1.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  809. var uvs = new Float32Array(buffer.length);
  810. uvs.set(buffer);
  811. normalizeUVs(uvs);
  812. tempVertexData.set(uvs, uvKind);
  813. }
  814. else if (semantic === "JOINT") {
  815. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  816. tempVertexData.matricesIndices.set(buffer);
  817. }
  818. else if (semantic === "WEIGHT") {
  819. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  820. tempVertexData.matricesWeights.set(buffer);
  821. }
  822. else if (semantic === "COLOR") {
  823. tempVertexData.colors = new Float32Array(buffer.length);
  824. tempVertexData.colors.set(buffer);
  825. }
  826. }
  827. // Indices
  828. accessor = gltfRuntime.accessors[primitive.indices];
  829. if (accessor) {
  830. buffer = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  831. tempVertexData.indices = new Int32Array(buffer.length);
  832. tempVertexData.indices.set(buffer);
  833. indexCounts.push(tempVertexData.indices.length);
  834. }
  835. else {
  836. // Set indices on the fly
  837. var indices = [];
  838. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  839. indices.push(j);
  840. }
  841. tempVertexData.indices = new Int32Array(indices);
  842. indexCounts.push(tempVertexData.indices.length);
  843. }
  844. if (!vertexData) {
  845. vertexData = tempVertexData;
  846. }
  847. else {
  848. vertexData.merge(tempVertexData);
  849. }
  850. // Sub material
  851. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  852. subMaterials.push(material_1 === null ? glTFLoaderUtils_1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  853. // Update vertices start and index start
  854. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  855. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  856. }
  857. }
  858. var material;
  859. if (subMaterials.length > 1) {
  860. material = new babylonjs_1.MultiMaterial("multimat" + id, gltfRuntime.scene);
  861. material.subMaterials = subMaterials;
  862. }
  863. else {
  864. material = new babylonjs_1.StandardMaterial("multimat" + id, gltfRuntime.scene);
  865. }
  866. if (subMaterials.length === 1) {
  867. material = subMaterials[0];
  868. }
  869. if (!newMesh.material) {
  870. newMesh.material = material;
  871. }
  872. // Apply geometry
  873. new babylonjs_1.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  874. newMesh.computeWorldMatrix(true);
  875. // Apply submeshes
  876. newMesh.subMeshes = [];
  877. var index = 0;
  878. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  879. var meshID = meshes[meshIndex];
  880. var mesh = gltfRuntime.meshes[meshID];
  881. if (!mesh) {
  882. continue;
  883. }
  884. for (var i = 0; i < mesh.primitives.length; i++) {
  885. if (mesh.primitives[i].mode !== 4) {
  886. //continue;
  887. }
  888. babylonjs_1.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  889. index++;
  890. }
  891. }
  892. // Finish
  893. return newMesh;
  894. };
  895. /**
  896. * Configure node transformation from position, rotation and scaling
  897. */
  898. var configureNode = function (newNode, position, rotation, scaling) {
  899. if (newNode.position) {
  900. newNode.position = position;
  901. }
  902. if (newNode.rotationQuaternion || newNode.rotation) {
  903. newNode.rotationQuaternion = rotation;
  904. }
  905. if (newNode.scaling) {
  906. newNode.scaling = scaling;
  907. }
  908. };
  909. /**
  910. * Configures node from transformation matrix
  911. */
  912. var configureNodeFromMatrix = function (newNode, node, parent) {
  913. if (node.matrix) {
  914. var position = new babylonjs_1.Vector3(0, 0, 0);
  915. var rotation = new babylonjs_1.Quaternion();
  916. var scaling = new babylonjs_1.Vector3(0, 0, 0);
  917. var mat = babylonjs_1.Matrix.FromArray(node.matrix);
  918. mat.decompose(scaling, rotation, position);
  919. configureNode(newNode, position, rotation, scaling);
  920. }
  921. else if (node.translation && node.rotation && node.scale) {
  922. configureNode(newNode, babylonjs_1.Vector3.FromArray(node.translation), babylonjs_1.Quaternion.FromArray(node.rotation), babylonjs_1.Vector3.FromArray(node.scale));
  923. }
  924. newNode.computeWorldMatrix(true);
  925. };
  926. /**
  927. * Imports a node
  928. */
  929. var importNode = function (gltfRuntime, node, id, parent) {
  930. var lastNode = null;
  931. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  932. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  933. return null;
  934. }
  935. }
  936. // Meshes
  937. if (node.skin) {
  938. if (node.meshes) {
  939. var skin = gltfRuntime.skins[node.skin];
  940. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  941. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  942. if (newMesh.skeleton === null) {
  943. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  944. if (!skin.babylonSkeleton) {
  945. skin.babylonSkeleton = newMesh.skeleton;
  946. }
  947. }
  948. lastNode = newMesh;
  949. }
  950. }
  951. else if (node.meshes) {
  952. /**
  953. * Improve meshes property
  954. */
  955. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  956. lastNode = newMesh;
  957. }
  958. // Lights
  959. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  960. var light = gltfRuntime.lights[node.light];
  961. if (light) {
  962. if (light.type === "ambient") {
  963. var ambienLight = light[light.type];
  964. var hemiLight = new babylonjs_1.HemisphericLight(node.light, babylonjs_1.Vector3.Zero(), gltfRuntime.scene);
  965. hemiLight.name = node.name || "";
  966. if (ambienLight.color) {
  967. hemiLight.diffuse = babylonjs_1.Color3.FromArray(ambienLight.color);
  968. }
  969. lastNode = hemiLight;
  970. }
  971. else if (light.type === "directional") {
  972. var directionalLight = light[light.type];
  973. var dirLight = new babylonjs_1.DirectionalLight(node.light, babylonjs_1.Vector3.Zero(), gltfRuntime.scene);
  974. dirLight.name = node.name || "";
  975. if (directionalLight.color) {
  976. dirLight.diffuse = babylonjs_1.Color3.FromArray(directionalLight.color);
  977. }
  978. lastNode = dirLight;
  979. }
  980. else if (light.type === "point") {
  981. var pointLight = light[light.type];
  982. var ptLight = new babylonjs_1.PointLight(node.light, babylonjs_1.Vector3.Zero(), gltfRuntime.scene);
  983. ptLight.name = node.name || "";
  984. if (pointLight.color) {
  985. ptLight.diffuse = babylonjs_1.Color3.FromArray(pointLight.color);
  986. }
  987. lastNode = ptLight;
  988. }
  989. else if (light.type === "spot") {
  990. var spotLight = light[light.type];
  991. var spLight = new babylonjs_1.SpotLight(node.light, babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  992. spLight.name = node.name || "";
  993. if (spotLight.color) {
  994. spLight.diffuse = babylonjs_1.Color3.FromArray(spotLight.color);
  995. }
  996. if (spotLight.fallOfAngle) {
  997. spLight.angle = spotLight.fallOfAngle;
  998. }
  999. if (spotLight.fallOffExponent) {
  1000. spLight.exponent = spotLight.fallOffExponent;
  1001. }
  1002. lastNode = spLight;
  1003. }
  1004. }
  1005. }
  1006. // Cameras
  1007. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1008. var camera = gltfRuntime.cameras[node.camera];
  1009. if (camera) {
  1010. if (camera.type === "orthographic") {
  1011. var orthoCamera = new babylonjs_1.FreeCamera(node.camera, babylonjs_1.Vector3.Zero(), gltfRuntime.scene, false);
  1012. orthoCamera.name = node.name || "";
  1013. orthoCamera.mode = babylonjs_1.Camera.ORTHOGRAPHIC_CAMERA;
  1014. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1015. lastNode = orthoCamera;
  1016. }
  1017. else if (camera.type === "perspective") {
  1018. var perspectiveCamera = camera[camera.type];
  1019. var persCamera = new babylonjs_1.FreeCamera(node.camera, babylonjs_1.Vector3.Zero(), gltfRuntime.scene, false);
  1020. persCamera.name = node.name || "";
  1021. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1022. if (!perspectiveCamera.aspectRatio) {
  1023. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  1024. }
  1025. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  1026. persCamera.maxZ = perspectiveCamera.zfar;
  1027. persCamera.minZ = perspectiveCamera.znear;
  1028. }
  1029. lastNode = persCamera;
  1030. }
  1031. }
  1032. }
  1033. // Empty node
  1034. if (!node.jointName) {
  1035. if (node.babylonNode) {
  1036. return node.babylonNode;
  1037. }
  1038. else if (lastNode === null) {
  1039. var dummy = new babylonjs_1.Mesh(node.name || "", gltfRuntime.scene);
  1040. node.babylonNode = dummy;
  1041. lastNode = dummy;
  1042. }
  1043. }
  1044. if (lastNode !== null) {
  1045. if (node.matrix && lastNode instanceof babylonjs_1.Mesh) {
  1046. configureNodeFromMatrix(lastNode, node, parent);
  1047. }
  1048. else {
  1049. var translation = node.translation || [0, 0, 0];
  1050. var rotation = node.rotation || [0, 0, 0, 1];
  1051. var scale = node.scale || [1, 1, 1];
  1052. configureNode(lastNode, babylonjs_1.Vector3.FromArray(translation), babylonjs_1.Quaternion.FromArray(rotation), babylonjs_1.Vector3.FromArray(scale));
  1053. }
  1054. lastNode.updateCache(true);
  1055. node.babylonNode = lastNode;
  1056. }
  1057. return lastNode;
  1058. };
  1059. /**
  1060. * Traverses nodes and creates them
  1061. */
  1062. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  1063. if (meshIncluded === void 0) { meshIncluded = false; }
  1064. var node = gltfRuntime.nodes[id];
  1065. var newNode = null;
  1066. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  1067. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  1068. meshIncluded = true;
  1069. }
  1070. else {
  1071. meshIncluded = false;
  1072. }
  1073. }
  1074. else {
  1075. meshIncluded = true;
  1076. }
  1077. if (!node.jointName && meshIncluded) {
  1078. newNode = importNode(gltfRuntime, node, id, parent);
  1079. if (newNode !== null) {
  1080. newNode.id = id;
  1081. newNode.parent = parent;
  1082. }
  1083. }
  1084. if (node.children) {
  1085. for (var i = 0; i < node.children.length; i++) {
  1086. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  1087. }
  1088. }
  1089. };
  1090. /**
  1091. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  1092. */
  1093. var postLoad = function (gltfRuntime) {
  1094. // Nodes
  1095. var currentScene = gltfRuntime.currentScene;
  1096. if (currentScene) {
  1097. for (var i = 0; i < currentScene.nodes.length; i++) {
  1098. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1099. }
  1100. }
  1101. else {
  1102. for (var thing in gltfRuntime.scenes) {
  1103. currentScene = gltfRuntime.scenes[thing];
  1104. for (var i = 0; i < currentScene.nodes.length; i++) {
  1105. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1106. }
  1107. }
  1108. }
  1109. // Set animations
  1110. loadAnimations(gltfRuntime);
  1111. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  1112. var skeleton = gltfRuntime.scene.skeletons[i];
  1113. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1114. }
  1115. };
  1116. /**
  1117. * onBind shaderrs callback to set uniforms and matrices
  1118. */
  1119. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  1120. var materialValues = material.values || technique.parameters;
  1121. for (var unif in unTreatedUniforms) {
  1122. var uniform = unTreatedUniforms[unif];
  1123. var type = uniform.type;
  1124. if (type === glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT2 || type === glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT3 || type === glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT4) {
  1125. if (uniform.semantic && !uniform.source && !uniform.node) {
  1126. glTFLoaderUtils_1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1127. }
  1128. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1129. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  1130. if (source === null) {
  1131. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  1132. }
  1133. if (source === null) {
  1134. continue;
  1135. }
  1136. glTFLoaderUtils_1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1137. }
  1138. }
  1139. else {
  1140. var value = materialValues[technique.uniforms[unif]];
  1141. if (!value) {
  1142. continue;
  1143. }
  1144. if (type === glTFLoaderInterfaces_1.EParameterType.SAMPLER_2D) {
  1145. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  1146. if (texture === null || texture === undefined) {
  1147. continue;
  1148. }
  1149. shaderMaterial.getEffect().setTexture(unif, texture);
  1150. }
  1151. else {
  1152. glTFLoaderUtils_1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  1153. }
  1154. }
  1155. }
  1156. onSuccess(shaderMaterial);
  1157. };
  1158. /**
  1159. * Prepare uniforms to send the only one time
  1160. * Loads the appropriate textures
  1161. */
  1162. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1163. var materialValues = material.values || technique.parameters;
  1164. var techniqueUniforms = technique.uniforms;
  1165. /**
  1166. * Prepare values here (not matrices)
  1167. */
  1168. for (var unif in unTreatedUniforms) {
  1169. var uniform = unTreatedUniforms[unif];
  1170. var type = uniform.type;
  1171. var value = materialValues[techniqueUniforms[unif]];
  1172. if (value === undefined) {
  1173. // In case the value is the same for all materials
  1174. value = uniform.value;
  1175. }
  1176. if (!value) {
  1177. continue;
  1178. }
  1179. var onLoadTexture = function (uniformName) {
  1180. return function (texture) {
  1181. if (uniform.value && uniformName) {
  1182. // Static uniform
  1183. shaderMaterial.setTexture(uniformName, texture);
  1184. delete unTreatedUniforms[uniformName];
  1185. }
  1186. };
  1187. };
  1188. // Texture (sampler2D)
  1189. if (type === glTFLoaderInterfaces_1.EParameterType.SAMPLER_2D) {
  1190. glTFLoaderExtension_1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  1191. }
  1192. // Others
  1193. else {
  1194. if (uniform.value && glTFLoaderUtils_1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1195. // Static uniform
  1196. delete unTreatedUniforms[unif];
  1197. }
  1198. }
  1199. }
  1200. };
  1201. /**
  1202. * Shader compilation failed
  1203. */
  1204. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1205. return function (effect, error) {
  1206. shaderMaterial.dispose(true);
  1207. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1208. };
  1209. };
  1210. /**
  1211. * Shader compilation success
  1212. */
  1213. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1214. return function (_) {
  1215. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1216. shaderMaterial.onBind = function (mesh) {
  1217. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1218. };
  1219. };
  1220. };
  1221. /**
  1222. * Returns the appropriate uniform if already handled by babylon
  1223. */
  1224. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1225. for (var unif in technique.uniforms) {
  1226. var uniform = technique.uniforms[unif];
  1227. var uniformParameter = technique.parameters[uniform];
  1228. if (tokenizer.currentIdentifier === unif) {
  1229. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1230. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1231. if (transformIndex !== -1) {
  1232. delete unTreatedUniforms[unif];
  1233. return babylonTransforms[transformIndex];
  1234. }
  1235. }
  1236. }
  1237. }
  1238. return tokenizer.currentIdentifier;
  1239. };
  1240. /**
  1241. * All shaders loaded. Create materials one by one
  1242. */
  1243. var importMaterials = function (gltfRuntime) {
  1244. // Create materials
  1245. for (var mat in gltfRuntime.materials) {
  1246. glTFLoaderExtension_1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1247. }
  1248. };
  1249. /**
  1250. * Implementation of the base glTF spec
  1251. * @hidden
  1252. */
  1253. var GLTFLoaderBase = /** @class */ (function () {
  1254. function GLTFLoaderBase() {
  1255. }
  1256. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1257. var gltfRuntime = {
  1258. extensions: {},
  1259. accessors: {},
  1260. buffers: {},
  1261. bufferViews: {},
  1262. meshes: {},
  1263. lights: {},
  1264. cameras: {},
  1265. nodes: {},
  1266. images: {},
  1267. textures: {},
  1268. shaders: {},
  1269. programs: {},
  1270. samplers: {},
  1271. techniques: {},
  1272. materials: {},
  1273. animations: {},
  1274. skins: {},
  1275. extensionsUsed: [],
  1276. scenes: {},
  1277. buffersCount: 0,
  1278. shaderscount: 0,
  1279. scene: scene,
  1280. rootUrl: rootUrl,
  1281. loadedBufferCount: 0,
  1282. loadedBufferViews: {},
  1283. loadedShaderCount: 0,
  1284. importOnlyMeshes: false,
  1285. dummyNodes: []
  1286. };
  1287. // Parse
  1288. if (parsedData.extensions) {
  1289. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1290. }
  1291. if (parsedData.extensionsUsed) {
  1292. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1293. }
  1294. if (parsedData.buffers) {
  1295. parseBuffers(parsedData.buffers, gltfRuntime);
  1296. }
  1297. if (parsedData.bufferViews) {
  1298. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1299. }
  1300. if (parsedData.accessors) {
  1301. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1302. }
  1303. if (parsedData.meshes) {
  1304. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1305. }
  1306. if (parsedData.lights) {
  1307. parseObject(parsedData.lights, "lights", gltfRuntime);
  1308. }
  1309. if (parsedData.cameras) {
  1310. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1311. }
  1312. if (parsedData.nodes) {
  1313. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1314. }
  1315. if (parsedData.images) {
  1316. parseObject(parsedData.images, "images", gltfRuntime);
  1317. }
  1318. if (parsedData.textures) {
  1319. parseObject(parsedData.textures, "textures", gltfRuntime);
  1320. }
  1321. if (parsedData.shaders) {
  1322. parseShaders(parsedData.shaders, gltfRuntime);
  1323. }
  1324. if (parsedData.programs) {
  1325. parseObject(parsedData.programs, "programs", gltfRuntime);
  1326. }
  1327. if (parsedData.samplers) {
  1328. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1329. }
  1330. if (parsedData.techniques) {
  1331. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1332. }
  1333. if (parsedData.materials) {
  1334. parseObject(parsedData.materials, "materials", gltfRuntime);
  1335. }
  1336. if (parsedData.animations) {
  1337. parseObject(parsedData.animations, "animations", gltfRuntime);
  1338. }
  1339. if (parsedData.skins) {
  1340. parseObject(parsedData.skins, "skins", gltfRuntime);
  1341. }
  1342. if (parsedData.scenes) {
  1343. gltfRuntime.scenes = parsedData.scenes;
  1344. }
  1345. if (parsedData.scene && parsedData.scenes) {
  1346. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1347. }
  1348. return gltfRuntime;
  1349. };
  1350. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1351. var buffer = gltfRuntime.buffers[id];
  1352. if (babylonjs_1.Tools.IsBase64(buffer.uri)) {
  1353. setTimeout(function () { return onSuccess(new Uint8Array(babylonjs_1.Tools.DecodeBase64(buffer.uri))); });
  1354. }
  1355. else {
  1356. babylonjs_1.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  1357. if (request) {
  1358. onError(request.status + " " + request.statusText);
  1359. }
  1360. });
  1361. }
  1362. };
  1363. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1364. var texture = gltfRuntime.textures[id];
  1365. if (!texture || !texture.source) {
  1366. onError("");
  1367. return;
  1368. }
  1369. if (texture.babylonTexture) {
  1370. onSuccess(null);
  1371. return;
  1372. }
  1373. var source = gltfRuntime.images[texture.source];
  1374. if (babylonjs_1.Tools.IsBase64(source.uri)) {
  1375. setTimeout(function () { return onSuccess(new Uint8Array(babylonjs_1.Tools.DecodeBase64(source.uri))); });
  1376. }
  1377. else {
  1378. babylonjs_1.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  1379. if (request) {
  1380. onError(request.status + " " + request.statusText);
  1381. }
  1382. });
  1383. }
  1384. };
  1385. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1386. var texture = gltfRuntime.textures[id];
  1387. if (texture.babylonTexture) {
  1388. onSuccess(texture.babylonTexture);
  1389. return;
  1390. }
  1391. var sampler = gltfRuntime.samplers[texture.sampler];
  1392. var createMipMaps = (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1393. (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1394. (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1395. (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1396. var samplingMode = babylonjs_1.Texture.BILINEAR_SAMPLINGMODE;
  1397. var blob = buffer == null ? new Blob() : new Blob([buffer]);
  1398. var blobURL = URL.createObjectURL(blob);
  1399. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1400. var newTexture = new babylonjs_1.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1401. if (sampler.wrapS !== undefined) {
  1402. newTexture.wrapU = glTFLoaderUtils_1.GLTFUtils.GetWrapMode(sampler.wrapS);
  1403. }
  1404. if (sampler.wrapT !== undefined) {
  1405. newTexture.wrapV = glTFLoaderUtils_1.GLTFUtils.GetWrapMode(sampler.wrapT);
  1406. }
  1407. newTexture.name = id;
  1408. texture.babylonTexture = newTexture;
  1409. onSuccess(newTexture);
  1410. };
  1411. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1412. var shader = gltfRuntime.shaders[id];
  1413. if (babylonjs_1.Tools.IsBase64(shader.uri)) {
  1414. var shaderString = atob(shader.uri.split(",")[1]);
  1415. if (onSuccess) {
  1416. onSuccess(shaderString);
  1417. }
  1418. }
  1419. else {
  1420. babylonjs_1.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  1421. if (request && onError) {
  1422. onError(request.status + " " + request.statusText);
  1423. }
  1424. });
  1425. }
  1426. };
  1427. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1428. var material = gltfRuntime.materials[id];
  1429. if (!material.technique) {
  1430. if (onError) {
  1431. onError("No technique found.");
  1432. }
  1433. return;
  1434. }
  1435. var technique = gltfRuntime.techniques[material.technique];
  1436. if (!technique) {
  1437. var defaultMaterial = new babylonjs_1.StandardMaterial(id, gltfRuntime.scene);
  1438. defaultMaterial.diffuseColor = new babylonjs_1.Color3(0.5, 0.5, 0.5);
  1439. defaultMaterial.sideOrientation = babylonjs_1.Material.CounterClockWiseSideOrientation;
  1440. onSuccess(defaultMaterial);
  1441. return;
  1442. }
  1443. var program = gltfRuntime.programs[technique.program];
  1444. var states = technique.states;
  1445. var vertexShader = babylonjs_1.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1446. var pixelShader = babylonjs_1.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1447. var newVertexShader = "";
  1448. var newPixelShader = "";
  1449. var vertexTokenizer = new Tokenizer(vertexShader);
  1450. var pixelTokenizer = new Tokenizer(pixelShader);
  1451. var unTreatedUniforms = {};
  1452. var uniforms = [];
  1453. var attributes = [];
  1454. var samplers = [];
  1455. // Fill uniform, sampler2D and attributes
  1456. for (var unif in technique.uniforms) {
  1457. var uniform = technique.uniforms[unif];
  1458. var uniformParameter = technique.parameters[uniform];
  1459. unTreatedUniforms[unif] = uniformParameter;
  1460. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1461. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1462. if (transformIndex !== -1) {
  1463. uniforms.push(babylonTransforms[transformIndex]);
  1464. delete unTreatedUniforms[unif];
  1465. }
  1466. else {
  1467. uniforms.push(unif);
  1468. }
  1469. }
  1470. else if (uniformParameter.type === glTFLoaderInterfaces_1.EParameterType.SAMPLER_2D) {
  1471. samplers.push(unif);
  1472. }
  1473. else {
  1474. uniforms.push(unif);
  1475. }
  1476. }
  1477. for (var attr in technique.attributes) {
  1478. var attribute = technique.attributes[attr];
  1479. var attributeParameter = technique.parameters[attribute];
  1480. if (attributeParameter.semantic) {
  1481. var name_1 = getAttribute(attributeParameter);
  1482. if (name_1) {
  1483. attributes.push(name_1);
  1484. }
  1485. }
  1486. }
  1487. // Configure vertex shader
  1488. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1489. var tokenType = vertexTokenizer.currentToken;
  1490. if (tokenType !== ETokenType.IDENTIFIER) {
  1491. newVertexShader += vertexTokenizer.currentString;
  1492. continue;
  1493. }
  1494. var foundAttribute = false;
  1495. for (var attr in technique.attributes) {
  1496. var attribute = technique.attributes[attr];
  1497. var attributeParameter = technique.parameters[attribute];
  1498. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1499. newVertexShader += getAttribute(attributeParameter);
  1500. foundAttribute = true;
  1501. break;
  1502. }
  1503. }
  1504. if (foundAttribute) {
  1505. continue;
  1506. }
  1507. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1508. }
  1509. // Configure pixel shader
  1510. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1511. var tokenType = pixelTokenizer.currentToken;
  1512. if (tokenType !== ETokenType.IDENTIFIER) {
  1513. newPixelShader += pixelTokenizer.currentString;
  1514. continue;
  1515. }
  1516. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1517. }
  1518. // Create shader material
  1519. var shaderPath = {
  1520. vertex: program.vertexShader + id,
  1521. fragment: program.fragmentShader + id
  1522. };
  1523. var options = {
  1524. attributes: attributes,
  1525. uniforms: uniforms,
  1526. samplers: samplers,
  1527. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1528. };
  1529. babylonjs_1.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1530. babylonjs_1.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1531. var shaderMaterial = new babylonjs_1.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1532. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1533. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1534. shaderMaterial.sideOrientation = babylonjs_1.Material.CounterClockWiseSideOrientation;
  1535. if (states && states.functions) {
  1536. var functions = states.functions;
  1537. if (functions.cullFace && functions.cullFace[0] !== glTFLoaderInterfaces_1.ECullingType.BACK) {
  1538. shaderMaterial.backFaceCulling = false;
  1539. }
  1540. var blendFunc = functions.blendFuncSeparate;
  1541. if (blendFunc) {
  1542. if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  1543. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_COMBINE;
  1544. }
  1545. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ZERO && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  1546. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_ONEONE;
  1547. }
  1548. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ZERO && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  1549. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_ADD;
  1550. }
  1551. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.ZERO && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  1552. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_SUBTRACT;
  1553. }
  1554. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.DST_COLOR && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ZERO && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  1555. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_MULTIPLY;
  1556. }
  1557. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  1558. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_MAXIMIZED;
  1559. }
  1560. }
  1561. }
  1562. };
  1563. return GLTFLoaderBase;
  1564. }());
  1565. exports.GLTFLoaderBase = GLTFLoaderBase;
  1566. /**
  1567. * glTF V1 Loader
  1568. * @hidden
  1569. */
  1570. var GLTFLoader = /** @class */ (function () {
  1571. function GLTFLoader() {
  1572. this.state = null;
  1573. }
  1574. GLTFLoader.RegisterExtension = function (extension) {
  1575. if (GLTFLoader.Extensions[extension.name]) {
  1576. babylonjs_1.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1577. return;
  1578. }
  1579. GLTFLoader.Extensions[extension.name] = extension;
  1580. };
  1581. GLTFLoader.prototype.dispose = function () {
  1582. // do nothing
  1583. };
  1584. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  1585. var _this = this;
  1586. scene.useRightHandedSystem = true;
  1587. glTFLoaderExtension_1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1588. gltfRuntime.importOnlyMeshes = true;
  1589. if (meshesNames === "") {
  1590. gltfRuntime.importMeshesNames = [];
  1591. }
  1592. else if (typeof meshesNames === "string") {
  1593. gltfRuntime.importMeshesNames = [meshesNames];
  1594. }
  1595. else if (meshesNames && !(meshesNames instanceof Array)) {
  1596. gltfRuntime.importMeshesNames = [meshesNames];
  1597. }
  1598. else {
  1599. gltfRuntime.importMeshesNames = [];
  1600. babylonjs_1.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1601. }
  1602. // Create nodes
  1603. _this._createNodes(gltfRuntime);
  1604. var meshes = new Array();
  1605. var skeletons = new Array();
  1606. // Fill arrays of meshes and skeletons
  1607. for (var nde in gltfRuntime.nodes) {
  1608. var node = gltfRuntime.nodes[nde];
  1609. if (node.babylonNode instanceof babylonjs_1.AbstractMesh) {
  1610. meshes.push(node.babylonNode);
  1611. }
  1612. }
  1613. for (var skl in gltfRuntime.skins) {
  1614. var skin = gltfRuntime.skins[skl];
  1615. if (skin.babylonSkeleton instanceof babylonjs_1.Skeleton) {
  1616. skeletons.push(skin.babylonSkeleton);
  1617. }
  1618. }
  1619. // Load buffers, shaders, materials, etc.
  1620. _this._loadBuffersAsync(gltfRuntime, function () {
  1621. _this._loadShadersAsync(gltfRuntime, function () {
  1622. importMaterials(gltfRuntime);
  1623. postLoad(gltfRuntime);
  1624. if (!glTFFileLoader_1.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1625. onSuccess(meshes, skeletons);
  1626. }
  1627. });
  1628. }, onProgress);
  1629. if (glTFFileLoader_1.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1630. onSuccess(meshes, skeletons);
  1631. }
  1632. }, onError);
  1633. return true;
  1634. };
  1635. /**
  1636. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  1637. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  1638. * @param scene the scene the meshes should be added to
  1639. * @param data gltf data containing information of the meshes in a loaded file
  1640. * @param rootUrl root url to load from
  1641. * @param onProgress event that fires when loading progress has occured
  1642. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  1643. */
  1644. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  1645. var _this = this;
  1646. return new Promise(function (resolve, reject) {
  1647. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  1648. resolve({
  1649. meshes: meshes,
  1650. particleSystems: [],
  1651. skeletons: skeletons,
  1652. animationGroups: []
  1653. });
  1654. }, onProgress, function (message) {
  1655. reject(new Error(message));
  1656. });
  1657. });
  1658. };
  1659. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  1660. var _this = this;
  1661. scene.useRightHandedSystem = true;
  1662. glTFLoaderExtension_1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1663. // Load runtime extensios
  1664. glTFLoaderExtension_1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  1665. // Create nodes
  1666. _this._createNodes(gltfRuntime);
  1667. // Load buffers, shaders, materials, etc.
  1668. _this._loadBuffersAsync(gltfRuntime, function () {
  1669. _this._loadShadersAsync(gltfRuntime, function () {
  1670. importMaterials(gltfRuntime);
  1671. postLoad(gltfRuntime);
  1672. if (!glTFFileLoader_1.GLTFFileLoader.IncrementalLoading) {
  1673. onSuccess();
  1674. }
  1675. });
  1676. });
  1677. if (glTFFileLoader_1.GLTFFileLoader.IncrementalLoading) {
  1678. onSuccess();
  1679. }
  1680. }, onError);
  1681. }, onError);
  1682. };
  1683. /**
  1684. * Imports all objects from a loaded gltf file and adds them to the scene
  1685. * @param scene the scene the objects should be added to
  1686. * @param data gltf data containing information of the meshes in a loaded file
  1687. * @param rootUrl root url to load from
  1688. * @param onProgress event that fires when loading progress has occured
  1689. * @returns a promise which completes when objects have been loaded to the scene
  1690. */
  1691. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  1692. var _this = this;
  1693. return new Promise(function (resolve, reject) {
  1694. _this._loadAsync(scene, data, rootUrl, function () {
  1695. resolve();
  1696. }, onProgress, function (message) {
  1697. reject(new Error(message));
  1698. });
  1699. });
  1700. };
  1701. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1702. var hasShaders = false;
  1703. var processShader = function (sha, shader) {
  1704. glTFLoaderExtension_1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1705. if (shaderString instanceof ArrayBuffer) {
  1706. return;
  1707. }
  1708. gltfRuntime.loadedShaderCount++;
  1709. if (shaderString) {
  1710. babylonjs_1.Effect.ShadersStore[sha + (shader.type === glTFLoaderInterfaces_1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1711. }
  1712. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1713. onload();
  1714. }
  1715. }, function () {
  1716. babylonjs_1.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1717. });
  1718. };
  1719. for (var sha in gltfRuntime.shaders) {
  1720. hasShaders = true;
  1721. var shader = gltfRuntime.shaders[sha];
  1722. if (shader) {
  1723. processShader.bind(this, sha, shader)();
  1724. }
  1725. else {
  1726. babylonjs_1.Tools.Error("No shader named: " + sha);
  1727. }
  1728. }
  1729. if (!hasShaders) {
  1730. onload();
  1731. }
  1732. };
  1733. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  1734. var hasBuffers = false;
  1735. var processBuffer = function (buf, buffer) {
  1736. glTFLoaderExtension_1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  1737. gltfRuntime.loadedBufferCount++;
  1738. if (bufferView) {
  1739. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1740. babylonjs_1.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1741. }
  1742. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1743. }
  1744. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1745. onLoad();
  1746. }
  1747. }, function () {
  1748. babylonjs_1.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1749. });
  1750. };
  1751. for (var buf in gltfRuntime.buffers) {
  1752. hasBuffers = true;
  1753. var buffer = gltfRuntime.buffers[buf];
  1754. if (buffer) {
  1755. processBuffer.bind(this, buf, buffer)();
  1756. }
  1757. else {
  1758. babylonjs_1.Tools.Error("No buffer named: " + buf);
  1759. }
  1760. }
  1761. if (!hasBuffers) {
  1762. onLoad();
  1763. }
  1764. };
  1765. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  1766. var currentScene = gltfRuntime.currentScene;
  1767. if (currentScene) {
  1768. // Only one scene even if multiple scenes are defined
  1769. for (var i = 0; i < currentScene.nodes.length; i++) {
  1770. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1771. }
  1772. }
  1773. else {
  1774. // Load all scenes
  1775. for (var thing in gltfRuntime.scenes) {
  1776. currentScene = gltfRuntime.scenes[thing];
  1777. for (var i = 0; i < currentScene.nodes.length; i++) {
  1778. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1779. }
  1780. }
  1781. }
  1782. };
  1783. GLTFLoader.Extensions = {};
  1784. return GLTFLoader;
  1785. }());
  1786. exports.GLTFLoader = GLTFLoader;
  1787. glTFFileLoader_1.GLTFFileLoader._CreateGLTF1Loader = function () { return new GLTFLoader(); };
  1788. /***/ }),
  1789. /***/ "./src/glTF/1.0/glTFLoaderExtension.ts":
  1790. /*!*********************************************!*\
  1791. !*** ./src/glTF/1.0/glTFLoaderExtension.ts ***!
  1792. \*********************************************/
  1793. /*! no static exports found */
  1794. /***/ (function(module, exports, __webpack_require__) {
  1795. "use strict";
  1796. Object.defineProperty(exports, "__esModule", { value: true });
  1797. var glTFLoader_1 = __webpack_require__(/*! ./glTFLoader */ "./src/glTF/1.0/glTFLoader.ts");
  1798. /** @hidden */
  1799. var GLTFLoaderExtension = /** @class */ (function () {
  1800. function GLTFLoaderExtension(name) {
  1801. this._name = name;
  1802. }
  1803. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  1804. get: function () {
  1805. return this._name;
  1806. },
  1807. enumerable: true,
  1808. configurable: true
  1809. });
  1810. /**
  1811. * Defines an override for loading the runtime
  1812. * Return true to stop further extensions from loading the runtime
  1813. */
  1814. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1815. return false;
  1816. };
  1817. /**
  1818. * Defines an onverride for creating gltf runtime
  1819. * Return true to stop further extensions from creating the runtime
  1820. */
  1821. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  1822. return false;
  1823. };
  1824. /**
  1825. * Defines an override for loading buffers
  1826. * Return true to stop further extensions from loading this buffer
  1827. */
  1828. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1829. return false;
  1830. };
  1831. /**
  1832. * Defines an override for loading texture buffers
  1833. * Return true to stop further extensions from loading this texture data
  1834. */
  1835. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1836. return false;
  1837. };
  1838. /**
  1839. * Defines an override for creating textures
  1840. * Return true to stop further extensions from loading this texture
  1841. */
  1842. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1843. return false;
  1844. };
  1845. /**
  1846. * Defines an override for loading shader strings
  1847. * Return true to stop further extensions from loading this shader data
  1848. */
  1849. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1850. return false;
  1851. };
  1852. /**
  1853. * Defines an override for loading materials
  1854. * Return true to stop further extensions from loading this material
  1855. */
  1856. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1857. return false;
  1858. };
  1859. // ---------
  1860. // Utilities
  1861. // ---------
  1862. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1863. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1864. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  1865. }, function () {
  1866. setTimeout(function () {
  1867. if (!onSuccess) {
  1868. return;
  1869. }
  1870. onSuccess(glTFLoader_1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  1871. });
  1872. });
  1873. };
  1874. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  1875. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1876. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  1877. }, function () {
  1878. setTimeout(function () {
  1879. onSuccess();
  1880. });
  1881. });
  1882. };
  1883. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1884. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1885. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  1886. }, function () {
  1887. glTFLoader_1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  1888. });
  1889. };
  1890. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  1891. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  1892. if (buffer) {
  1893. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1894. }
  1895. }, onError);
  1896. };
  1897. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1898. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1899. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  1900. }, function () {
  1901. glTFLoader_1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  1902. });
  1903. };
  1904. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1905. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1906. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  1907. }, function () {
  1908. glTFLoader_1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  1909. });
  1910. };
  1911. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1912. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1913. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  1914. }, function () {
  1915. glTFLoader_1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  1916. });
  1917. };
  1918. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1919. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1920. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1921. }, function () {
  1922. glTFLoader_1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1923. });
  1924. };
  1925. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  1926. for (var extensionName in glTFLoader_1.GLTFLoader.Extensions) {
  1927. var loaderExtension = glTFLoader_1.GLTFLoader.Extensions[extensionName];
  1928. if (func(loaderExtension)) {
  1929. return;
  1930. }
  1931. }
  1932. defaultFunc();
  1933. };
  1934. return GLTFLoaderExtension;
  1935. }());
  1936. exports.GLTFLoaderExtension = GLTFLoaderExtension;
  1937. /***/ }),
  1938. /***/ "./src/glTF/1.0/glTFLoaderInterfaces.ts":
  1939. /*!**********************************************!*\
  1940. !*** ./src/glTF/1.0/glTFLoaderInterfaces.ts ***!
  1941. \**********************************************/
  1942. /*! no static exports found */
  1943. /***/ (function(module, exports, __webpack_require__) {
  1944. "use strict";
  1945. Object.defineProperty(exports, "__esModule", { value: true });
  1946. /**
  1947. * Enums
  1948. * @hidden
  1949. */
  1950. var EComponentType;
  1951. (function (EComponentType) {
  1952. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  1953. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  1954. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  1955. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  1956. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  1957. })(EComponentType = exports.EComponentType || (exports.EComponentType = {}));
  1958. /** @hidden */
  1959. var EShaderType;
  1960. (function (EShaderType) {
  1961. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  1962. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  1963. })(EShaderType = exports.EShaderType || (exports.EShaderType = {}));
  1964. /** @hidden */
  1965. var EParameterType;
  1966. (function (EParameterType) {
  1967. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  1968. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  1969. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  1970. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  1971. EParameterType[EParameterType["INT"] = 5124] = "INT";
  1972. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  1973. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  1974. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  1975. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  1976. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  1977. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  1978. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  1979. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  1980. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  1981. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  1982. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  1983. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  1984. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  1985. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  1986. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  1987. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  1988. })(EParameterType = exports.EParameterType || (exports.EParameterType = {}));
  1989. /** @hidden */
  1990. var ETextureWrapMode;
  1991. (function (ETextureWrapMode) {
  1992. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  1993. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  1994. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  1995. })(ETextureWrapMode = exports.ETextureWrapMode || (exports.ETextureWrapMode = {}));
  1996. /** @hidden */
  1997. var ETextureFilterType;
  1998. (function (ETextureFilterType) {
  1999. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  2000. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  2001. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  2002. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  2003. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  2004. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  2005. })(ETextureFilterType = exports.ETextureFilterType || (exports.ETextureFilterType = {}));
  2006. /** @hidden */
  2007. var ETextureFormat;
  2008. (function (ETextureFormat) {
  2009. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  2010. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  2011. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  2012. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  2013. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  2014. })(ETextureFormat = exports.ETextureFormat || (exports.ETextureFormat = {}));
  2015. /** @hidden */
  2016. var ECullingType;
  2017. (function (ECullingType) {
  2018. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  2019. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  2020. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  2021. })(ECullingType = exports.ECullingType || (exports.ECullingType = {}));
  2022. /** @hidden */
  2023. var EBlendingFunction;
  2024. (function (EBlendingFunction) {
  2025. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  2026. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  2027. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  2028. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  2029. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  2030. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  2031. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  2032. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  2033. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  2034. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  2035. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  2036. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  2037. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  2038. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  2039. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  2040. })(EBlendingFunction = exports.EBlendingFunction || (exports.EBlendingFunction = {}));
  2041. /***/ }),
  2042. /***/ "./src/glTF/1.0/glTFLoaderUtils.ts":
  2043. /*!*****************************************!*\
  2044. !*** ./src/glTF/1.0/glTFLoaderUtils.ts ***!
  2045. \*****************************************/
  2046. /*! no static exports found */
  2047. /***/ (function(module, exports, __webpack_require__) {
  2048. "use strict";
  2049. Object.defineProperty(exports, "__esModule", { value: true });
  2050. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  2051. var glTFLoaderInterfaces_1 = __webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/1.0/glTFLoaderInterfaces.ts");
  2052. /**
  2053. * Utils functions for GLTF
  2054. * @hidden
  2055. */
  2056. var GLTFUtils = /** @class */ (function () {
  2057. function GLTFUtils() {
  2058. }
  2059. /**
  2060. * Sets the given "parameter" matrix
  2061. * @param scene: the Scene object
  2062. * @param source: the source node where to pick the matrix
  2063. * @param parameter: the GLTF technique parameter
  2064. * @param uniformName: the name of the shader's uniform
  2065. * @param shaderMaterial: the shader material
  2066. */
  2067. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  2068. var mat = null;
  2069. if (parameter.semantic === "MODEL") {
  2070. mat = source.getWorldMatrix();
  2071. }
  2072. else if (parameter.semantic === "PROJECTION") {
  2073. mat = scene.getProjectionMatrix();
  2074. }
  2075. else if (parameter.semantic === "VIEW") {
  2076. mat = scene.getViewMatrix();
  2077. }
  2078. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  2079. mat = babylonjs_1.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  2080. }
  2081. else if (parameter.semantic === "MODELVIEW") {
  2082. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  2083. }
  2084. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  2085. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  2086. }
  2087. else if (parameter.semantic === "MODELINVERSE") {
  2088. mat = source.getWorldMatrix().invert();
  2089. }
  2090. else if (parameter.semantic === "VIEWINVERSE") {
  2091. mat = scene.getViewMatrix().invert();
  2092. }
  2093. else if (parameter.semantic === "PROJECTIONINVERSE") {
  2094. mat = scene.getProjectionMatrix().invert();
  2095. }
  2096. else if (parameter.semantic === "MODELVIEWINVERSE") {
  2097. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  2098. }
  2099. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  2100. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  2101. }
  2102. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  2103. mat = babylonjs_1.Matrix.Transpose(source.getWorldMatrix().invert());
  2104. }
  2105. else {
  2106. debugger;
  2107. }
  2108. if (mat) {
  2109. switch (parameter.type) {
  2110. case glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT2:
  2111. shaderMaterial.setMatrix2x2(uniformName, babylonjs_1.Matrix.GetAsMatrix2x2(mat));
  2112. break;
  2113. case glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT3:
  2114. shaderMaterial.setMatrix3x3(uniformName, babylonjs_1.Matrix.GetAsMatrix3x3(mat));
  2115. break;
  2116. case glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT4:
  2117. shaderMaterial.setMatrix(uniformName, mat);
  2118. break;
  2119. default: break;
  2120. }
  2121. }
  2122. };
  2123. /**
  2124. * Sets the given "parameter" matrix
  2125. * @param shaderMaterial: the shader material
  2126. * @param uniform: the name of the shader's uniform
  2127. * @param value: the value of the uniform
  2128. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  2129. */
  2130. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  2131. switch (type) {
  2132. case glTFLoaderInterfaces_1.EParameterType.FLOAT:
  2133. shaderMaterial.setFloat(uniform, value);
  2134. return true;
  2135. case glTFLoaderInterfaces_1.EParameterType.FLOAT_VEC2:
  2136. shaderMaterial.setVector2(uniform, babylonjs_1.Vector2.FromArray(value));
  2137. return true;
  2138. case glTFLoaderInterfaces_1.EParameterType.FLOAT_VEC3:
  2139. shaderMaterial.setVector3(uniform, babylonjs_1.Vector3.FromArray(value));
  2140. return true;
  2141. case glTFLoaderInterfaces_1.EParameterType.FLOAT_VEC4:
  2142. shaderMaterial.setVector4(uniform, babylonjs_1.Vector4.FromArray(value));
  2143. return true;
  2144. default: return false;
  2145. }
  2146. };
  2147. /**
  2148. * Returns the wrap mode of the texture
  2149. * @param mode: the mode value
  2150. */
  2151. GLTFUtils.GetWrapMode = function (mode) {
  2152. switch (mode) {
  2153. case glTFLoaderInterfaces_1.ETextureWrapMode.CLAMP_TO_EDGE: return babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  2154. case glTFLoaderInterfaces_1.ETextureWrapMode.MIRRORED_REPEAT: return babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  2155. case glTFLoaderInterfaces_1.ETextureWrapMode.REPEAT: return babylonjs_1.Texture.WRAP_ADDRESSMODE;
  2156. default: return babylonjs_1.Texture.WRAP_ADDRESSMODE;
  2157. }
  2158. };
  2159. /**
  2160. * Returns the byte stride giving an accessor
  2161. * @param accessor: the GLTF accessor objet
  2162. */
  2163. GLTFUtils.GetByteStrideFromType = function (accessor) {
  2164. // Needs this function since "byteStride" isn't requiered in glTF format
  2165. var type = accessor.type;
  2166. switch (type) {
  2167. case "VEC2": return 2;
  2168. case "VEC3": return 3;
  2169. case "VEC4": return 4;
  2170. case "MAT2": return 4;
  2171. case "MAT3": return 9;
  2172. case "MAT4": return 16;
  2173. default: return 1;
  2174. }
  2175. };
  2176. /**
  2177. * Returns the texture filter mode giving a mode value
  2178. * @param mode: the filter mode value
  2179. */
  2180. GLTFUtils.GetTextureFilterMode = function (mode) {
  2181. switch (mode) {
  2182. case glTFLoaderInterfaces_1.ETextureFilterType.LINEAR:
  2183. case glTFLoaderInterfaces_1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  2184. case glTFLoaderInterfaces_1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return babylonjs_1.Texture.TRILINEAR_SAMPLINGMODE;
  2185. case glTFLoaderInterfaces_1.ETextureFilterType.NEAREST:
  2186. case glTFLoaderInterfaces_1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return babylonjs_1.Texture.NEAREST_SAMPLINGMODE;
  2187. default: return babylonjs_1.Texture.BILINEAR_SAMPLINGMODE;
  2188. }
  2189. };
  2190. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  2191. var byteOffset = bufferView.byteOffset + byteOffset;
  2192. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  2193. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  2194. throw new Error("Buffer access is out of range");
  2195. }
  2196. var buffer = loadedBufferView.buffer;
  2197. byteOffset += loadedBufferView.byteOffset;
  2198. switch (componentType) {
  2199. case glTFLoaderInterfaces_1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  2200. case glTFLoaderInterfaces_1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  2201. case glTFLoaderInterfaces_1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  2202. case glTFLoaderInterfaces_1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  2203. default: return new Float32Array(buffer, byteOffset, byteLength);
  2204. }
  2205. };
  2206. /**
  2207. * Returns a buffer from its accessor
  2208. * @param gltfRuntime: the GLTF runtime
  2209. * @param accessor: the GLTF accessor
  2210. */
  2211. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  2212. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  2213. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  2214. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  2215. };
  2216. /**
  2217. * Decodes a buffer view into a string
  2218. * @param view: the buffer view
  2219. */
  2220. GLTFUtils.DecodeBufferToText = function (view) {
  2221. var result = "";
  2222. var length = view.byteLength;
  2223. for (var i = 0; i < length; ++i) {
  2224. result += String.fromCharCode(view[i]);
  2225. }
  2226. return result;
  2227. };
  2228. /**
  2229. * Returns the default material of gltf. Related to
  2230. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  2231. * @param scene: the Babylon.js scene
  2232. */
  2233. GLTFUtils.GetDefaultMaterial = function (scene) {
  2234. if (!GLTFUtils._DefaultMaterial) {
  2235. babylonjs_1.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  2236. "precision highp float;",
  2237. "",
  2238. "uniform mat4 worldView;",
  2239. "uniform mat4 projection;",
  2240. "",
  2241. "attribute vec3 position;",
  2242. "",
  2243. "void main(void)",
  2244. "{",
  2245. " gl_Position = projection * worldView * vec4(position, 1.0);",
  2246. "}"
  2247. ].join("\n");
  2248. babylonjs_1.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  2249. "precision highp float;",
  2250. "",
  2251. "uniform vec4 u_emission;",
  2252. "",
  2253. "void main(void)",
  2254. "{",
  2255. " gl_FragColor = u_emission;",
  2256. "}"
  2257. ].join("\n");
  2258. var shaderPath = {
  2259. vertex: "GLTFDefaultMaterial",
  2260. fragment: "GLTFDefaultMaterial"
  2261. };
  2262. var options = {
  2263. attributes: ["position"],
  2264. uniforms: ["worldView", "projection", "u_emission"],
  2265. samplers: new Array(),
  2266. needAlphaBlending: false
  2267. };
  2268. GLTFUtils._DefaultMaterial = new babylonjs_1.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  2269. GLTFUtils._DefaultMaterial.setColor4("u_emission", new babylonjs_1.Color4(0.5, 0.5, 0.5, 1.0));
  2270. }
  2271. return GLTFUtils._DefaultMaterial;
  2272. };
  2273. // The GLTF default material
  2274. GLTFUtils._DefaultMaterial = null;
  2275. return GLTFUtils;
  2276. }());
  2277. exports.GLTFUtils = GLTFUtils;
  2278. /***/ }),
  2279. /***/ "./src/glTF/1.0/glTFMaterialsCommonExtension.ts":
  2280. /*!******************************************************!*\
  2281. !*** ./src/glTF/1.0/glTFMaterialsCommonExtension.ts ***!
  2282. \******************************************************/
  2283. /*! no static exports found */
  2284. /***/ (function(module, exports, __webpack_require__) {
  2285. "use strict";
  2286. var __extends = (this && this.__extends) || (function () {
  2287. var extendStatics = function (d, b) {
  2288. extendStatics = Object.setPrototypeOf ||
  2289. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2290. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2291. return extendStatics(d, b);
  2292. }
  2293. return function (d, b) {
  2294. extendStatics(d, b);
  2295. function __() { this.constructor = d; }
  2296. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2297. };
  2298. })();
  2299. Object.defineProperty(exports, "__esModule", { value: true });
  2300. var _1 = __webpack_require__(/*! . */ "./src/glTF/1.0/index.ts");
  2301. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  2302. var glTFLoader_1 = __webpack_require__(/*! ./glTFLoader */ "./src/glTF/1.0/glTFLoader.ts");
  2303. /** @hidden */
  2304. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  2305. __extends(GLTFMaterialsCommonExtension, _super);
  2306. function GLTFMaterialsCommonExtension() {
  2307. return _super.call(this, "KHR_materials_common") || this;
  2308. }
  2309. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2310. if (!gltfRuntime.extensions) {
  2311. return false;
  2312. }
  2313. var extension = gltfRuntime.extensions[this.name];
  2314. if (!extension) {
  2315. return false;
  2316. }
  2317. // Create lights
  2318. var lights = extension.lights;
  2319. if (lights) {
  2320. for (var thing in lights) {
  2321. var light = lights[thing];
  2322. switch (light.type) {
  2323. case "ambient":
  2324. var ambientLight = new babylonjs_1.HemisphericLight(light.name, new babylonjs_1.Vector3(0, 1, 0), gltfRuntime.scene);
  2325. var ambient = light.ambient;
  2326. if (ambient) {
  2327. ambientLight.diffuse = babylonjs_1.Color3.FromArray(ambient.color || [1, 1, 1]);
  2328. }
  2329. break;
  2330. case "point":
  2331. var pointLight = new babylonjs_1.PointLight(light.name, new babylonjs_1.Vector3(10, 10, 10), gltfRuntime.scene);
  2332. var point = light.point;
  2333. if (point) {
  2334. pointLight.diffuse = babylonjs_1.Color3.FromArray(point.color || [1, 1, 1]);
  2335. }
  2336. break;
  2337. case "directional":
  2338. var dirLight = new babylonjs_1.DirectionalLight(light.name, new babylonjs_1.Vector3(0, -1, 0), gltfRuntime.scene);
  2339. var directional = light.directional;
  2340. if (directional) {
  2341. dirLight.diffuse = babylonjs_1.Color3.FromArray(directional.color || [1, 1, 1]);
  2342. }
  2343. break;
  2344. case "spot":
  2345. var spot = light.spot;
  2346. if (spot) {
  2347. var spotLight = new babylonjs_1.SpotLight(light.name, new babylonjs_1.Vector3(0, 10, 0), new babylonjs_1.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  2348. spotLight.diffuse = babylonjs_1.Color3.FromArray(spot.color || [1, 1, 1]);
  2349. }
  2350. break;
  2351. default:
  2352. babylonjs_1.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  2353. break;
  2354. }
  2355. }
  2356. }
  2357. return false;
  2358. };
  2359. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2360. var material = gltfRuntime.materials[id];
  2361. if (!material || !material.extensions) {
  2362. return false;
  2363. }
  2364. var extension = material.extensions[this.name];
  2365. if (!extension) {
  2366. return false;
  2367. }
  2368. var standardMaterial = new babylonjs_1.StandardMaterial(id, gltfRuntime.scene);
  2369. standardMaterial.sideOrientation = babylonjs_1.Material.CounterClockWiseSideOrientation;
  2370. if (extension.technique === "CONSTANT") {
  2371. standardMaterial.disableLighting = true;
  2372. }
  2373. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2374. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2375. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2376. // Ambient
  2377. if (typeof extension.values.ambient === "string") {
  2378. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2379. }
  2380. else {
  2381. standardMaterial.ambientColor = babylonjs_1.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2382. }
  2383. // Diffuse
  2384. if (typeof extension.values.diffuse === "string") {
  2385. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2386. }
  2387. else {
  2388. standardMaterial.diffuseColor = babylonjs_1.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2389. }
  2390. // Emission
  2391. if (typeof extension.values.emission === "string") {
  2392. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2393. }
  2394. else {
  2395. standardMaterial.emissiveColor = babylonjs_1.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2396. }
  2397. // Specular
  2398. if (typeof extension.values.specular === "string") {
  2399. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2400. }
  2401. else {
  2402. standardMaterial.specularColor = babylonjs_1.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2403. }
  2404. return true;
  2405. };
  2406. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2407. // Create buffer from texture url
  2408. _1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2409. // Create texture from buffer
  2410. _1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2411. }, onError);
  2412. };
  2413. return GLTFMaterialsCommonExtension;
  2414. }(_1.GLTFLoaderExtension));
  2415. exports.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  2416. glTFLoader_1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  2417. /***/ }),
  2418. /***/ "./src/glTF/1.0/index.ts":
  2419. /*!*******************************!*\
  2420. !*** ./src/glTF/1.0/index.ts ***!
  2421. \*******************************/
  2422. /*! no static exports found */
  2423. /***/ (function(module, exports, __webpack_require__) {
  2424. "use strict";
  2425. function __export(m) {
  2426. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  2427. }
  2428. Object.defineProperty(exports, "__esModule", { value: true });
  2429. __export(__webpack_require__(/*! ./glTFBinaryExtension */ "./src/glTF/1.0/glTFBinaryExtension.ts"));
  2430. __export(__webpack_require__(/*! ./glTFLoader */ "./src/glTF/1.0/glTFLoader.ts"));
  2431. __export(__webpack_require__(/*! ./glTFLoaderExtension */ "./src/glTF/1.0/glTFLoaderExtension.ts"));
  2432. __export(__webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/1.0/glTFLoaderInterfaces.ts"));
  2433. __export(__webpack_require__(/*! ./glTFLoaderUtils */ "./src/glTF/1.0/glTFLoaderUtils.ts"));
  2434. __export(__webpack_require__(/*! ./glTFMaterialsCommonExtension */ "./src/glTF/1.0/glTFMaterialsCommonExtension.ts"));
  2435. /***/ }),
  2436. /***/ "./src/glTF/glTFFileLoader.ts":
  2437. /*!************************************!*\
  2438. !*** ./src/glTF/glTFFileLoader.ts ***!
  2439. \************************************/
  2440. /*! no static exports found */
  2441. /***/ (function(module, exports, __webpack_require__) {
  2442. "use strict";
  2443. Object.defineProperty(exports, "__esModule", { value: true });
  2444. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  2445. /**
  2446. * Mode that determines the coordinate system to use.
  2447. */
  2448. var GLTFLoaderCoordinateSystemMode;
  2449. (function (GLTFLoaderCoordinateSystemMode) {
  2450. /**
  2451. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  2452. */
  2453. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  2454. /**
  2455. * Sets the useRightHandedSystem flag on the scene.
  2456. */
  2457. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  2458. })(GLTFLoaderCoordinateSystemMode = exports.GLTFLoaderCoordinateSystemMode || (exports.GLTFLoaderCoordinateSystemMode = {}));
  2459. /**
  2460. * Mode that determines what animations will start.
  2461. */
  2462. var GLTFLoaderAnimationStartMode;
  2463. (function (GLTFLoaderAnimationStartMode) {
  2464. /**
  2465. * No animation will start.
  2466. */
  2467. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  2468. /**
  2469. * The first animation will start.
  2470. */
  2471. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  2472. /**
  2473. * All animations will start.
  2474. */
  2475. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  2476. })(GLTFLoaderAnimationStartMode = exports.GLTFLoaderAnimationStartMode || (exports.GLTFLoaderAnimationStartMode = {}));
  2477. /**
  2478. * Loader state.
  2479. */
  2480. var GLTFLoaderState;
  2481. (function (GLTFLoaderState) {
  2482. /**
  2483. * The asset is loading.
  2484. */
  2485. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  2486. /**
  2487. * The asset is ready for rendering.
  2488. */
  2489. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  2490. /**
  2491. * The asset is completely loaded.
  2492. */
  2493. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  2494. })(GLTFLoaderState = exports.GLTFLoaderState || (exports.GLTFLoaderState = {}));
  2495. /**
  2496. * File loader for loading glTF files into a scene.
  2497. */
  2498. var GLTFFileLoader = /** @class */ (function () {
  2499. function GLTFFileLoader() {
  2500. // --------------
  2501. // Common options
  2502. // --------------
  2503. /**
  2504. * Raised when the asset has been parsed
  2505. */
  2506. this.onParsedObservable = new babylonjs_1.Observable();
  2507. // ----------
  2508. // V2 options
  2509. // ----------
  2510. /**
  2511. * The coordinate system mode. Defaults to AUTO.
  2512. */
  2513. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  2514. /**
  2515. * The animation start mode. Defaults to FIRST.
  2516. */
  2517. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  2518. /**
  2519. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  2520. */
  2521. this.compileMaterials = false;
  2522. /**
  2523. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  2524. */
  2525. this.useClipPlane = false;
  2526. /**
  2527. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  2528. */
  2529. this.compileShadowGenerators = false;
  2530. /**
  2531. * Defines if the Alpha blended materials are only applied as coverage.
  2532. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  2533. * If true, no extra effects are applied to transparent pixels.
  2534. */
  2535. this.transparencyAsCoverage = false;
  2536. /**
  2537. * Function called before loading a url referenced by the asset.
  2538. */
  2539. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  2540. /**
  2541. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  2542. */
  2543. this.onMeshLoadedObservable = new babylonjs_1.Observable();
  2544. /**
  2545. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  2546. */
  2547. this.onTextureLoadedObservable = new babylonjs_1.Observable();
  2548. /**
  2549. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  2550. */
  2551. this.onMaterialLoadedObservable = new babylonjs_1.Observable();
  2552. /**
  2553. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  2554. */
  2555. this.onCameraLoadedObservable = new babylonjs_1.Observable();
  2556. /**
  2557. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  2558. * For assets with LODs, raised when all of the LODs are complete.
  2559. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  2560. */
  2561. this.onCompleteObservable = new babylonjs_1.Observable();
  2562. /**
  2563. * Observable raised when an error occurs.
  2564. */
  2565. this.onErrorObservable = new babylonjs_1.Observable();
  2566. /**
  2567. * Observable raised after the loader is disposed.
  2568. */
  2569. this.onDisposeObservable = new babylonjs_1.Observable();
  2570. /**
  2571. * Observable raised after a loader extension is created.
  2572. * Set additional options for a loader extension in this event.
  2573. */
  2574. this.onExtensionLoadedObservable = new babylonjs_1.Observable();
  2575. /**
  2576. * Defines if the loader should validate the asset.
  2577. */
  2578. this.validate = false;
  2579. /**
  2580. * Observable raised after validation when validate is set to true. The event data is the result of the validation.
  2581. */
  2582. this.onValidatedObservable = new babylonjs_1.Observable();
  2583. this._loader = null;
  2584. /**
  2585. * Name of the loader ("gltf")
  2586. */
  2587. this.name = "gltf";
  2588. /**
  2589. * Supported file extensions of the loader (.gltf, .glb)
  2590. */
  2591. this.extensions = {
  2592. ".gltf": { isBinary: false },
  2593. ".glb": { isBinary: true }
  2594. };
  2595. this._logIndentLevel = 0;
  2596. this._loggingEnabled = false;
  2597. /** @hidden */
  2598. this._log = this._logDisabled;
  2599. this._capturePerformanceCounters = false;
  2600. /** @hidden */
  2601. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  2602. /** @hidden */
  2603. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  2604. }
  2605. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  2606. /**
  2607. * Raised when the asset has been parsed
  2608. */
  2609. set: function (callback) {
  2610. if (this._onParsedObserver) {
  2611. this.onParsedObservable.remove(this._onParsedObserver);
  2612. }
  2613. this._onParsedObserver = this.onParsedObservable.add(callback);
  2614. },
  2615. enumerable: true,
  2616. configurable: true
  2617. });
  2618. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  2619. /**
  2620. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  2621. */
  2622. set: function (callback) {
  2623. if (this._onMeshLoadedObserver) {
  2624. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  2625. }
  2626. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  2627. },
  2628. enumerable: true,
  2629. configurable: true
  2630. });
  2631. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  2632. /**
  2633. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  2634. */
  2635. set: function (callback) {
  2636. if (this._onTextureLoadedObserver) {
  2637. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  2638. }
  2639. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  2640. },
  2641. enumerable: true,
  2642. configurable: true
  2643. });
  2644. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  2645. /**
  2646. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  2647. */
  2648. set: function (callback) {
  2649. if (this._onMaterialLoadedObserver) {
  2650. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  2651. }
  2652. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  2653. },
  2654. enumerable: true,
  2655. configurable: true
  2656. });
  2657. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  2658. /**
  2659. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  2660. */
  2661. set: function (callback) {
  2662. if (this._onCameraLoadedObserver) {
  2663. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  2664. }
  2665. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  2666. },
  2667. enumerable: true,
  2668. configurable: true
  2669. });
  2670. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  2671. /**
  2672. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  2673. * For assets with LODs, raised when all of the LODs are complete.
  2674. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  2675. */
  2676. set: function (callback) {
  2677. if (this._onCompleteObserver) {
  2678. this.onCompleteObservable.remove(this._onCompleteObserver);
  2679. }
  2680. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  2681. },
  2682. enumerable: true,
  2683. configurable: true
  2684. });
  2685. Object.defineProperty(GLTFFileLoader.prototype, "onError", {
  2686. /**
  2687. * Callback raised when an error occurs.
  2688. */
  2689. set: function (callback) {
  2690. if (this._onErrorObserver) {
  2691. this.onErrorObservable.remove(this._onErrorObserver);
  2692. }
  2693. this._onErrorObserver = this.onErrorObservable.add(callback);
  2694. },
  2695. enumerable: true,
  2696. configurable: true
  2697. });
  2698. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  2699. /**
  2700. * Callback raised after the loader is disposed.
  2701. */
  2702. set: function (callback) {
  2703. if (this._onDisposeObserver) {
  2704. this.onDisposeObservable.remove(this._onDisposeObserver);
  2705. }
  2706. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  2707. },
  2708. enumerable: true,
  2709. configurable: true
  2710. });
  2711. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  2712. /**
  2713. * Callback raised after a loader extension is created.
  2714. */
  2715. set: function (callback) {
  2716. if (this._onExtensionLoadedObserver) {
  2717. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  2718. }
  2719. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  2720. },
  2721. enumerable: true,
  2722. configurable: true
  2723. });
  2724. Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", {
  2725. /**
  2726. * Defines if the loader logging is enabled.
  2727. */
  2728. get: function () {
  2729. return this._loggingEnabled;
  2730. },
  2731. set: function (value) {
  2732. if (this._loggingEnabled === value) {
  2733. return;
  2734. }
  2735. this._loggingEnabled = value;
  2736. if (this._loggingEnabled) {
  2737. this._log = this._logEnabled;
  2738. }
  2739. else {
  2740. this._log = this._logDisabled;
  2741. }
  2742. },
  2743. enumerable: true,
  2744. configurable: true
  2745. });
  2746. Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", {
  2747. /**
  2748. * Defines if the loader should capture performance counters.
  2749. */
  2750. get: function () {
  2751. return this._capturePerformanceCounters;
  2752. },
  2753. set: function (value) {
  2754. if (this._capturePerformanceCounters === value) {
  2755. return;
  2756. }
  2757. this._capturePerformanceCounters = value;
  2758. if (this._capturePerformanceCounters) {
  2759. this._startPerformanceCounter = this._startPerformanceCounterEnabled;
  2760. this._endPerformanceCounter = this._endPerformanceCounterEnabled;
  2761. }
  2762. else {
  2763. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  2764. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  2765. }
  2766. },
  2767. enumerable: true,
  2768. configurable: true
  2769. });
  2770. Object.defineProperty(GLTFFileLoader.prototype, "onValidated", {
  2771. /**
  2772. * Callback raised after a loader extension is created.
  2773. */
  2774. set: function (callback) {
  2775. if (this._onValidatedObserver) {
  2776. this.onValidatedObservable.remove(this._onValidatedObserver);
  2777. }
  2778. this._onValidatedObserver = this.onValidatedObservable.add(callback);
  2779. },
  2780. enumerable: true,
  2781. configurable: true
  2782. });
  2783. /**
  2784. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  2785. */
  2786. GLTFFileLoader.prototype.dispose = function () {
  2787. if (this._loader) {
  2788. this._loader.dispose();
  2789. this._loader = null;
  2790. }
  2791. this._clear();
  2792. this.onDisposeObservable.notifyObservers(undefined);
  2793. this.onDisposeObservable.clear();
  2794. };
  2795. /** @hidden */
  2796. GLTFFileLoader.prototype._clear = function () {
  2797. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  2798. this.onMeshLoadedObservable.clear();
  2799. this.onTextureLoadedObservable.clear();
  2800. this.onMaterialLoadedObservable.clear();
  2801. this.onCameraLoadedObservable.clear();
  2802. this.onCompleteObservable.clear();
  2803. this.onExtensionLoadedObservable.clear();
  2804. };
  2805. /**
  2806. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  2807. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  2808. * @param scene the scene the meshes should be added to
  2809. * @param data the glTF data to load
  2810. * @param rootUrl root url to load from
  2811. * @param onProgress event that fires when loading progress has occured
  2812. * @param fileName Defines the name of the file to load
  2813. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  2814. */
  2815. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  2816. var _this = this;
  2817. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  2818. _this._log("Loading " + (fileName || ""));
  2819. _this._loader = _this._getLoader(loaderData);
  2820. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress, fileName);
  2821. });
  2822. };
  2823. /**
  2824. * Imports all objects from the loaded glTF data and adds them to the scene
  2825. * @param scene the scene the objects should be added to
  2826. * @param data the glTF data to load
  2827. * @param rootUrl root url to load from
  2828. * @param onProgress event that fires when loading progress has occured
  2829. * @param fileName Defines the name of the file to load
  2830. * @returns a promise which completes when objects have been loaded to the scene
  2831. */
  2832. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  2833. var _this = this;
  2834. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  2835. _this._log("Loading " + (fileName || ""));
  2836. _this._loader = _this._getLoader(loaderData);
  2837. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress, fileName);
  2838. });
  2839. };
  2840. /**
  2841. * Load into an asset container.
  2842. * @param scene The scene to load into
  2843. * @param data The data to import
  2844. * @param rootUrl The root url for scene and resources
  2845. * @param onProgress The callback when the load progresses
  2846. * @param fileName Defines the name of the file to load
  2847. * @returns The loaded asset container
  2848. */
  2849. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress, fileName) {
  2850. var _this = this;
  2851. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  2852. _this._log("Loading " + (fileName || ""));
  2853. _this._loader = _this._getLoader(loaderData);
  2854. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress, fileName).then(function (result) {
  2855. var container = new babylonjs_1.AssetContainer(scene);
  2856. Array.prototype.push.apply(container.meshes, result.meshes);
  2857. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  2858. Array.prototype.push.apply(container.skeletons, result.skeletons);
  2859. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  2860. container.removeAllFromScene();
  2861. return container;
  2862. });
  2863. });
  2864. };
  2865. /**
  2866. * If the data string can be loaded directly.
  2867. * @param data string contianing the file data
  2868. * @returns if the data can be loaded directly
  2869. */
  2870. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  2871. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  2872. };
  2873. /**
  2874. * Instantiates a glTF file loader plugin.
  2875. * @returns the created plugin
  2876. */
  2877. GLTFFileLoader.prototype.createPlugin = function () {
  2878. return new GLTFFileLoader();
  2879. };
  2880. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  2881. /**
  2882. * The loader state or null if the loader is not active.
  2883. */
  2884. get: function () {
  2885. return this._loader ? this._loader.state : null;
  2886. },
  2887. enumerable: true,
  2888. configurable: true
  2889. });
  2890. /**
  2891. * Returns a promise that resolves when the asset is completely loaded.
  2892. * @returns a promise that resolves when the asset is completely loaded.
  2893. */
  2894. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  2895. var _this = this;
  2896. return new Promise(function (resolve, reject) {
  2897. _this.onCompleteObservable.addOnce(function () {
  2898. resolve();
  2899. });
  2900. _this.onErrorObservable.addOnce(function (reason) {
  2901. reject(reason);
  2902. });
  2903. });
  2904. };
  2905. GLTFFileLoader.prototype._parseAsync = function (scene, data, rootUrl, fileName) {
  2906. var _this = this;
  2907. return Promise.resolve().then(function () {
  2908. var unpacked = (data instanceof ArrayBuffer) ? _this._unpackBinary(data) : { json: data, bin: null };
  2909. return _this._validateAsync(scene, unpacked.json, rootUrl, fileName).then(function () {
  2910. _this._startPerformanceCounter("Parse JSON");
  2911. _this._log("JSON length: " + unpacked.json.length);
  2912. var loaderData = {
  2913. json: JSON.parse(unpacked.json),
  2914. bin: unpacked.bin
  2915. };
  2916. _this._endPerformanceCounter("Parse JSON");
  2917. _this.onParsedObservable.notifyObservers(loaderData);
  2918. _this.onParsedObservable.clear();
  2919. return loaderData;
  2920. });
  2921. });
  2922. };
  2923. GLTFFileLoader.prototype._validateAsync = function (scene, json, rootUrl, fileName) {
  2924. var _this = this;
  2925. if (!this.validate || typeof GLTFValidator === "undefined") {
  2926. return Promise.resolve();
  2927. }
  2928. this._startPerformanceCounter("Validate JSON");
  2929. var options = {
  2930. externalResourceFunction: function (uri) {
  2931. return _this.preprocessUrlAsync(rootUrl + uri)
  2932. .then(function (url) { return scene._loadFileAsync(url, true, true); })
  2933. .then(function (data) { return new Uint8Array(data); });
  2934. }
  2935. };
  2936. if (fileName && fileName.substr(0, 5) !== "data:") {
  2937. options.uri = (rootUrl === "file:" ? fileName : "" + rootUrl + fileName);
  2938. }
  2939. return GLTFValidator.validateString(json, options).then(function (result) {
  2940. _this._endPerformanceCounter("Validate JSON");
  2941. _this.onValidatedObservable.notifyObservers(result);
  2942. _this.onValidatedObservable.clear();
  2943. }, function (reason) {
  2944. _this._endPerformanceCounter("Validate JSON");
  2945. babylonjs_1.Tools.Warn("Failed to validate: " + reason);
  2946. _this.onValidatedObservable.clear();
  2947. });
  2948. };
  2949. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  2950. var asset = loaderData.json.asset || {};
  2951. this._log("Asset version: " + asset.version);
  2952. asset.minVersion && this._log("Asset minimum version: " + asset.minVersion);
  2953. asset.generator && this._log("Asset generator: " + asset.generator);
  2954. var version = GLTFFileLoader._parseVersion(asset.version);
  2955. if (!version) {
  2956. throw new Error("Invalid version: " + asset.version);
  2957. }
  2958. if (asset.minVersion !== undefined) {
  2959. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  2960. if (!minVersion) {
  2961. throw new Error("Invalid minimum version: " + asset.minVersion);
  2962. }
  2963. if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
  2964. throw new Error("Incompatible minimum version: " + asset.minVersion);
  2965. }
  2966. }
  2967. var createLoaders = {
  2968. 1: GLTFFileLoader._CreateGLTF1Loader,
  2969. 2: GLTFFileLoader._CreateGLTF2Loader
  2970. };
  2971. var createLoader = createLoaders[version.major];
  2972. if (!createLoader) {
  2973. throw new Error("Unsupported version: " + asset.version);
  2974. }
  2975. return createLoader(this);
  2976. };
  2977. GLTFFileLoader.prototype._unpackBinary = function (data) {
  2978. this._startPerformanceCounter("Unpack binary");
  2979. this._log("Binary length: " + data.byteLength);
  2980. var Binary = {
  2981. Magic: 0x46546C67
  2982. };
  2983. var binaryReader = new BinaryReader(data);
  2984. var magic = binaryReader.readUint32();
  2985. if (magic !== Binary.Magic) {
  2986. throw new Error("Unexpected magic: " + magic);
  2987. }
  2988. var version = binaryReader.readUint32();
  2989. if (this.loggingEnabled) {
  2990. this._log("Binary version: " + version);
  2991. }
  2992. var unpacked;
  2993. switch (version) {
  2994. case 1: {
  2995. unpacked = this._unpackBinaryV1(binaryReader);
  2996. break;
  2997. }
  2998. case 2: {
  2999. unpacked = this._unpackBinaryV2(binaryReader);
  3000. break;
  3001. }
  3002. default: {
  3003. throw new Error("Unsupported version: " + version);
  3004. }
  3005. }
  3006. this._endPerformanceCounter("Unpack binary");
  3007. return unpacked;
  3008. };
  3009. GLTFFileLoader.prototype._unpackBinaryV1 = function (binaryReader) {
  3010. var ContentFormat = {
  3011. JSON: 0
  3012. };
  3013. var length = binaryReader.readUint32();
  3014. if (length != binaryReader.getLength()) {
  3015. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  3016. }
  3017. var contentLength = binaryReader.readUint32();
  3018. var contentFormat = binaryReader.readUint32();
  3019. var content;
  3020. switch (contentFormat) {
  3021. case ContentFormat.JSON: {
  3022. content = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength));
  3023. break;
  3024. }
  3025. default: {
  3026. throw new Error("Unexpected content format: " + contentFormat);
  3027. }
  3028. }
  3029. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  3030. var body = binaryReader.readUint8Array(bytesRemaining);
  3031. return {
  3032. json: content,
  3033. bin: body
  3034. };
  3035. };
  3036. GLTFFileLoader.prototype._unpackBinaryV2 = function (binaryReader) {
  3037. var ChunkFormat = {
  3038. JSON: 0x4E4F534A,
  3039. BIN: 0x004E4942
  3040. };
  3041. var length = binaryReader.readUint32();
  3042. if (length !== binaryReader.getLength()) {
  3043. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  3044. }
  3045. // JSON chunk
  3046. var chunkLength = binaryReader.readUint32();
  3047. var chunkFormat = binaryReader.readUint32();
  3048. if (chunkFormat !== ChunkFormat.JSON) {
  3049. throw new Error("First chunk format is not JSON");
  3050. }
  3051. var json = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength));
  3052. // Look for BIN chunk
  3053. var bin = null;
  3054. while (binaryReader.getPosition() < binaryReader.getLength()) {
  3055. var chunkLength_1 = binaryReader.readUint32();
  3056. var chunkFormat_1 = binaryReader.readUint32();
  3057. switch (chunkFormat_1) {
  3058. case ChunkFormat.JSON: {
  3059. throw new Error("Unexpected JSON chunk");
  3060. }
  3061. case ChunkFormat.BIN: {
  3062. bin = binaryReader.readUint8Array(chunkLength_1);
  3063. break;
  3064. }
  3065. default: {
  3066. // ignore unrecognized chunkFormat
  3067. binaryReader.skipBytes(chunkLength_1);
  3068. break;
  3069. }
  3070. }
  3071. }
  3072. return {
  3073. json: json,
  3074. bin: bin
  3075. };
  3076. };
  3077. GLTFFileLoader._parseVersion = function (version) {
  3078. if (version === "1.0" || version === "1.0.1") {
  3079. return {
  3080. major: 1,
  3081. minor: 0
  3082. };
  3083. }
  3084. var match = (version + "").match(/^(\d+)\.(\d+)/);
  3085. if (!match) {
  3086. return null;
  3087. }
  3088. return {
  3089. major: parseInt(match[1]),
  3090. minor: parseInt(match[2])
  3091. };
  3092. };
  3093. GLTFFileLoader._compareVersion = function (a, b) {
  3094. if (a.major > b.major) {
  3095. return 1;
  3096. }
  3097. if (a.major < b.major) {
  3098. return -1;
  3099. }
  3100. if (a.minor > b.minor) {
  3101. return 1;
  3102. }
  3103. if (a.minor < b.minor) {
  3104. return -1;
  3105. }
  3106. return 0;
  3107. };
  3108. GLTFFileLoader._decodeBufferToText = function (buffer) {
  3109. var result = "";
  3110. var length = buffer.byteLength;
  3111. for (var i = 0; i < length; i++) {
  3112. result += String.fromCharCode(buffer[i]);
  3113. }
  3114. return result;
  3115. };
  3116. /** @hidden */
  3117. GLTFFileLoader.prototype._logOpen = function (message) {
  3118. this._log(message);
  3119. this._logIndentLevel++;
  3120. };
  3121. /** @hidden */
  3122. GLTFFileLoader.prototype._logClose = function () {
  3123. --this._logIndentLevel;
  3124. };
  3125. GLTFFileLoader.prototype._logEnabled = function (message) {
  3126. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  3127. babylonjs_1.Tools.Log("" + spaces + message);
  3128. };
  3129. GLTFFileLoader.prototype._logDisabled = function (message) {
  3130. };
  3131. GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
  3132. babylonjs_1.Tools.StartPerformanceCounter(counterName);
  3133. };
  3134. GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
  3135. };
  3136. GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
  3137. babylonjs_1.Tools.EndPerformanceCounter(counterName);
  3138. };
  3139. GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
  3140. };
  3141. // ----------
  3142. // V1 options
  3143. // ----------
  3144. /**
  3145. * 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.
  3146. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  3147. * Defaults to true.
  3148. * @hidden
  3149. */
  3150. GLTFFileLoader.IncrementalLoading = true;
  3151. /**
  3152. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  3153. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  3154. * @hidden
  3155. */
  3156. GLTFFileLoader.HomogeneousCoordinates = false;
  3157. GLTFFileLoader._logSpaces = " ";
  3158. return GLTFFileLoader;
  3159. }());
  3160. exports.GLTFFileLoader = GLTFFileLoader;
  3161. var BinaryReader = /** @class */ (function () {
  3162. function BinaryReader(arrayBuffer) {
  3163. this._arrayBuffer = arrayBuffer;
  3164. this._dataView = new DataView(arrayBuffer);
  3165. this._byteOffset = 0;
  3166. }
  3167. BinaryReader.prototype.getPosition = function () {
  3168. return this._byteOffset;
  3169. };
  3170. BinaryReader.prototype.getLength = function () {
  3171. return this._arrayBuffer.byteLength;
  3172. };
  3173. BinaryReader.prototype.readUint32 = function () {
  3174. var value = this._dataView.getUint32(this._byteOffset, true);
  3175. this._byteOffset += 4;
  3176. return value;
  3177. };
  3178. BinaryReader.prototype.readUint8Array = function (length) {
  3179. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  3180. this._byteOffset += length;
  3181. return value;
  3182. };
  3183. BinaryReader.prototype.skipBytes = function (length) {
  3184. this._byteOffset += length;
  3185. };
  3186. return BinaryReader;
  3187. }());
  3188. if (babylonjs_1.SceneLoader) {
  3189. babylonjs_1.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  3190. }
  3191. /***/ }),
  3192. /***/ "babylonjs":
  3193. /*!****************************************************************************************************!*\
  3194. !*** external {"root":"BABYLON","commonjs":"babylonjs","commonjs2":"babylonjs","amd":"babylonjs"} ***!
  3195. \****************************************************************************************************/
  3196. /*! no static exports found */
  3197. /***/ (function(module, exports) {
  3198. module.exports = __WEBPACK_EXTERNAL_MODULE_babylonjs__;
  3199. /***/ })
  3200. /******/ });
  3201. });
  3202. //# sourceMappingURL=babylon.glTF1FileLoader.js.map