babylon.glTF1FileLoader.min.js 137 KB

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