babylon.glTF2FileLoader.js 121 KB

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