babylon.glTF2FileLoader.js 116 KB

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