babylon.glTF2FileLoader.js 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. var GLTFLoaderCoordinateSystemMode;
  5. (function (GLTFLoaderCoordinateSystemMode) {
  6. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  7. // NOTE: When scene.useRightHandedSystem is false, an additional transform will be added to the root to transform the data from right-handed to left-handed.
  8. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  9. // The glTF right-handed data is not transformed in any form and is loaded directly.
  10. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  11. // Sets the useRightHandedSystem flag on the scene.
  12. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  13. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  14. var GLTFFileLoader = (function () {
  15. function GLTFFileLoader() {
  16. // V2 options
  17. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  18. this.name = "gltf";
  19. this.extensions = {
  20. ".gltf": { isBinary: false },
  21. ".glb": { isBinary: true }
  22. };
  23. }
  24. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  25. var loaderData = GLTFFileLoader._parse(data, onError);
  26. if (!loaderData) {
  27. return;
  28. }
  29. if (this.onParsed) {
  30. this.onParsed(loaderData);
  31. }
  32. var loader = this._getLoader(loaderData, onError);
  33. if (!loader) {
  34. return;
  35. }
  36. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  37. };
  38. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  39. var loaderData = GLTFFileLoader._parse(data, onError);
  40. if (!loaderData) {
  41. return;
  42. }
  43. if (this.onParsed) {
  44. this.onParsed(loaderData);
  45. }
  46. var loader = this._getLoader(loaderData, onError);
  47. if (!loader) {
  48. return;
  49. }
  50. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  51. };
  52. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  53. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  54. };
  55. GLTFFileLoader._parse = function (data, onError) {
  56. try {
  57. if (data instanceof ArrayBuffer) {
  58. return GLTFFileLoader._parseBinary(data, onError);
  59. }
  60. return {
  61. json: JSON.parse(data),
  62. bin: null
  63. };
  64. }
  65. catch (e) {
  66. onError(e.message);
  67. return null;
  68. }
  69. };
  70. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  71. var loaderVersion = { major: 2, minor: 0 };
  72. var asset = loaderData.json.asset || {};
  73. var version = GLTFFileLoader._parseVersion(asset.version);
  74. if (!version) {
  75. onError("Invalid version: " + asset.version);
  76. return null;
  77. }
  78. if (asset.minVersion !== undefined) {
  79. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  80. if (!minVersion) {
  81. onError("Invalid minimum version: " + asset.minVersion);
  82. return null;
  83. }
  84. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  85. onError("Incompatible minimum version: " + asset.minVersion);
  86. return null;
  87. }
  88. }
  89. var createLoaders = {
  90. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  91. 2: GLTFFileLoader.CreateGLTFLoaderV2
  92. };
  93. var createLoader = createLoaders[version.major];
  94. if (!createLoader) {
  95. onError("Unsupported version: " + asset.version);
  96. return null;
  97. }
  98. return createLoader(this);
  99. };
  100. GLTFFileLoader._parseBinary = function (data, onError) {
  101. var Binary = {
  102. Magic: 0x46546C67
  103. };
  104. var binaryReader = new BinaryReader(data);
  105. var magic = binaryReader.readUint32();
  106. if (magic !== Binary.Magic) {
  107. onError("Unexpected magic: " + magic);
  108. return null;
  109. }
  110. var version = binaryReader.readUint32();
  111. switch (version) {
  112. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  113. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  114. }
  115. onError("Unsupported version: " + version);
  116. return null;
  117. };
  118. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  119. var ContentFormat = {
  120. JSON: 0
  121. };
  122. var length = binaryReader.readUint32();
  123. if (length != binaryReader.getLength()) {
  124. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  125. return null;
  126. }
  127. var contentLength = binaryReader.readUint32();
  128. var contentFormat = binaryReader.readUint32();
  129. var content;
  130. switch (contentFormat) {
  131. case ContentFormat.JSON:
  132. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  133. break;
  134. default:
  135. onError("Unexpected content format: " + contentFormat);
  136. return null;
  137. }
  138. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  139. var body = binaryReader.readUint8Array(bytesRemaining);
  140. return {
  141. json: content,
  142. bin: body
  143. };
  144. };
  145. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  146. var ChunkFormat = {
  147. JSON: 0x4E4F534A,
  148. BIN: 0x004E4942
  149. };
  150. var length = binaryReader.readUint32();
  151. if (length !== binaryReader.getLength()) {
  152. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  153. return null;
  154. }
  155. // JSON chunk
  156. var chunkLength = binaryReader.readUint32();
  157. var chunkFormat = binaryReader.readUint32();
  158. if (chunkFormat !== ChunkFormat.JSON) {
  159. onError("First chunk format is not JSON");
  160. return null;
  161. }
  162. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  163. // Look for BIN chunk
  164. var bin = null;
  165. while (binaryReader.getPosition() < binaryReader.getLength()) {
  166. chunkLength = binaryReader.readUint32();
  167. chunkFormat = binaryReader.readUint32();
  168. switch (chunkFormat) {
  169. case ChunkFormat.JSON:
  170. onError("Unexpected JSON chunk");
  171. return null;
  172. case ChunkFormat.BIN:
  173. bin = binaryReader.readUint8Array(chunkLength);
  174. break;
  175. default:
  176. // ignore unrecognized chunkFormat
  177. binaryReader.skipBytes(chunkLength);
  178. break;
  179. }
  180. }
  181. return {
  182. json: json,
  183. bin: bin
  184. };
  185. };
  186. GLTFFileLoader._parseVersion = function (version) {
  187. if (!version) {
  188. return null;
  189. }
  190. var parts = version.split(".");
  191. if (parts.length != 2) {
  192. return null;
  193. }
  194. var major = +parts[0];
  195. if (isNaN(major)) {
  196. return null;
  197. }
  198. var minor = +parts[1];
  199. if (isNaN(minor)) {
  200. return null;
  201. }
  202. return {
  203. major: major,
  204. minor: minor
  205. };
  206. };
  207. GLTFFileLoader._compareVersion = function (a, b) {
  208. if (a.major > b.major)
  209. return 1;
  210. if (a.major < b.major)
  211. return -1;
  212. if (a.minor > b.minor)
  213. return 1;
  214. if (a.minor < b.minor)
  215. return -1;
  216. return 0;
  217. };
  218. GLTFFileLoader._decodeBufferToText = function (view) {
  219. var result = "";
  220. var length = view.byteLength;
  221. for (var i = 0; i < length; ++i) {
  222. result += String.fromCharCode(view[i]);
  223. }
  224. return result;
  225. };
  226. // V1 options
  227. GLTFFileLoader.HomogeneousCoordinates = false;
  228. GLTFFileLoader.IncrementalLoading = true;
  229. return GLTFFileLoader;
  230. }());
  231. BABYLON.GLTFFileLoader = GLTFFileLoader;
  232. var BinaryReader = (function () {
  233. function BinaryReader(arrayBuffer) {
  234. this._arrayBuffer = arrayBuffer;
  235. this._dataView = new DataView(arrayBuffer);
  236. this._byteOffset = 0;
  237. }
  238. BinaryReader.prototype.getPosition = function () {
  239. return this._byteOffset;
  240. };
  241. BinaryReader.prototype.getLength = function () {
  242. return this._arrayBuffer.byteLength;
  243. };
  244. BinaryReader.prototype.readUint32 = function () {
  245. var value = this._dataView.getUint32(this._byteOffset, true);
  246. this._byteOffset += 4;
  247. return value;
  248. };
  249. BinaryReader.prototype.readUint8Array = function (length) {
  250. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  251. this._byteOffset += length;
  252. return value;
  253. };
  254. BinaryReader.prototype.skipBytes = function (length) {
  255. this._byteOffset += length;
  256. };
  257. return BinaryReader;
  258. }());
  259. if (BABYLON.SceneLoader) {
  260. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  261. }
  262. })(BABYLON || (BABYLON = {}));
  263. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  264. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  265. var BABYLON;
  266. (function (BABYLON) {
  267. var GLTF2;
  268. (function (GLTF2) {
  269. /**
  270. * Enums
  271. */
  272. var EComponentType;
  273. (function (EComponentType) {
  274. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  275. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  276. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  277. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  278. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  279. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  280. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  281. var EMeshPrimitiveMode;
  282. (function (EMeshPrimitiveMode) {
  283. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  284. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  285. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  286. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  287. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  288. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  289. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  290. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  291. var ETextureMagFilter;
  292. (function (ETextureMagFilter) {
  293. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  294. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  295. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  296. var ETextureMinFilter;
  297. (function (ETextureMinFilter) {
  298. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  299. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  300. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  301. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  302. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  303. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  304. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  305. var ETextureWrapMode;
  306. (function (ETextureWrapMode) {
  307. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  308. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  309. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  310. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  311. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  312. })(BABYLON || (BABYLON = {}));
  313. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  314. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  315. var BABYLON;
  316. (function (BABYLON) {
  317. var GLTF2;
  318. (function (GLTF2) {
  319. var GLTFLoaderTracker = (function () {
  320. function GLTFLoaderTracker(onComplete) {
  321. this._pendingCount = 0;
  322. this._callback = onComplete;
  323. }
  324. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  325. this._pendingCount++;
  326. };
  327. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  328. if (--this._pendingCount === 0) {
  329. this._callback();
  330. }
  331. };
  332. return GLTFLoaderTracker;
  333. }());
  334. var GLTFLoader = (function () {
  335. function GLTFLoader(parent) {
  336. this._renderReady = false;
  337. this._disposed = false;
  338. this._renderReadyObservable = new BABYLON.Observable();
  339. // Count of pending work that needs to complete before the asset is rendered.
  340. this._renderPendingCount = 0;
  341. // Count of pending work that needs to complete before the loader is disposed.
  342. this._loaderPendingCount = 0;
  343. this._loaderTrackers = new Array();
  344. this._parent = parent;
  345. }
  346. GLTFLoader.RegisterExtension = function (extension) {
  347. if (GLTFLoader.Extensions[extension.name]) {
  348. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  349. return;
  350. }
  351. GLTFLoader.Extensions[extension.name] = extension;
  352. // Keep the order of registration so that extensions registered first are called first.
  353. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  354. };
  355. GLTFLoader.prototype.dispose = function () {
  356. if (this._disposed) {
  357. return;
  358. }
  359. this._disposed = true;
  360. // Revoke object urls created during load
  361. if (this._gltf.textures) {
  362. this._gltf.textures.forEach(function (texture) {
  363. if (texture.url) {
  364. URL.revokeObjectURL(texture.url);
  365. }
  366. });
  367. }
  368. this._gltf = undefined;
  369. this._babylonScene = undefined;
  370. this._rootUrl = undefined;
  371. this._defaultMaterial = undefined;
  372. this._successCallback = undefined;
  373. this._errorCallback = undefined;
  374. this._renderReady = false;
  375. this._renderReadyObservable.clear();
  376. this._renderPendingCount = 0;
  377. this._loaderPendingCount = 0;
  378. };
  379. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  380. var _this = this;
  381. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  382. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  383. }, onProgress, onError);
  384. };
  385. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  386. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  387. };
  388. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  389. var _this = this;
  390. this._tryCatchOnError(function () {
  391. _this._loadData(data);
  392. _this._babylonScene = scene;
  393. _this._rootUrl = rootUrl;
  394. _this._successCallback = onSuccess;
  395. _this._progressCallback = onProgress;
  396. _this._errorCallback = onError;
  397. GLTF2.GLTFUtils.AssignIndices(_this._gltf.accessors);
  398. GLTF2.GLTFUtils.AssignIndices(_this._gltf.animations);
  399. GLTF2.GLTFUtils.AssignIndices(_this._gltf.buffers);
  400. GLTF2.GLTFUtils.AssignIndices(_this._gltf.bufferViews);
  401. GLTF2.GLTFUtils.AssignIndices(_this._gltf.images);
  402. GLTF2.GLTFUtils.AssignIndices(_this._gltf.materials);
  403. GLTF2.GLTFUtils.AssignIndices(_this._gltf.meshes);
  404. GLTF2.GLTFUtils.AssignIndices(_this._gltf.nodes);
  405. GLTF2.GLTFUtils.AssignIndices(_this._gltf.scenes);
  406. GLTF2.GLTFUtils.AssignIndices(_this._gltf.skins);
  407. GLTF2.GLTFUtils.AssignIndices(_this._gltf.textures);
  408. _this._addPendingData(_this);
  409. _this._loadDefaultScene(nodeNames);
  410. _this._loadAnimations();
  411. _this._removePendingData(_this);
  412. });
  413. };
  414. GLTFLoader.prototype._onError = function (message) {
  415. if (this._disposed) {
  416. return;
  417. }
  418. BABYLON.Tools.Error("glTF Loader: " + message);
  419. if (this._errorCallback) {
  420. this._errorCallback(message);
  421. }
  422. this.dispose();
  423. };
  424. GLTFLoader.prototype._onProgress = function (event) {
  425. if (this._disposed) {
  426. return;
  427. }
  428. if (this._progressCallback) {
  429. this._progressCallback(event);
  430. }
  431. };
  432. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  433. if (this._renderReady) {
  434. func();
  435. }
  436. else {
  437. this._renderReadyObservable.add(func);
  438. }
  439. };
  440. GLTFLoader.prototype._onRenderReady = function () {
  441. this._rootNode.babylonMesh.setEnabled(true);
  442. this._startAnimations();
  443. this._successCallback();
  444. this._renderReadyObservable.notifyObservers(this);
  445. if (this._parent.onReady) {
  446. this._parent.onReady();
  447. }
  448. };
  449. GLTFLoader.prototype._onComplete = function () {
  450. if (this._parent.onComplete) {
  451. this._parent.onComplete();
  452. }
  453. this.dispose();
  454. };
  455. GLTFLoader.prototype._loadData = function (data) {
  456. this._gltf = data.json;
  457. if (data.bin) {
  458. var buffers = this._gltf.buffers;
  459. if (buffers && buffers[0] && !buffers[0].uri) {
  460. var binaryBuffer = buffers[0];
  461. if (binaryBuffer.byteLength != data.bin.byteLength) {
  462. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  463. }
  464. binaryBuffer.loadedData = data.bin;
  465. }
  466. else {
  467. BABYLON.Tools.Warn("Unexpected BIN chunk");
  468. }
  469. }
  470. };
  471. GLTFLoader.prototype._getMeshes = function () {
  472. var meshes = [this._rootNode.babylonMesh];
  473. var nodes = this._gltf.nodes;
  474. if (nodes) {
  475. nodes.forEach(function (node) {
  476. if (node.babylonMesh) {
  477. meshes.push(node.babylonMesh);
  478. }
  479. });
  480. }
  481. return meshes;
  482. };
  483. GLTFLoader.prototype._getSkeletons = function () {
  484. var skeletons = new Array();
  485. var skins = this._gltf.skins;
  486. if (skins) {
  487. skins.forEach(function (skin) {
  488. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  489. skeletons.push(skin.babylonSkeleton);
  490. }
  491. });
  492. }
  493. return skeletons;
  494. };
  495. GLTFLoader.prototype._getAnimationTargets = function () {
  496. var targets = new Array();
  497. var animations = this._gltf.animations;
  498. if (animations) {
  499. animations.forEach(function (animation) {
  500. targets.push.apply(targets, animation.targets);
  501. });
  502. }
  503. return targets;
  504. };
  505. GLTFLoader.prototype._startAnimations = function () {
  506. var _this = this;
  507. this._getAnimationTargets().forEach(function (target) { return _this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); });
  508. };
  509. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  510. var scene = GLTF2.GLTFUtils.GetArrayItem(this._gltf.scenes, this._gltf.scene || 0);
  511. if (!scene) {
  512. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  513. }
  514. this._loadScene("scenes[" + scene.index + "]", scene, nodeNames);
  515. };
  516. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  517. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  518. switch (this._parent.coordinateSystemMode) {
  519. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  520. if (!this._babylonScene.useRightHandedSystem) {
  521. this._rootNode.babylonMesh.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  522. this._rootNode.babylonMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  523. }
  524. break;
  525. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  526. // do nothing
  527. break;
  528. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  529. this._babylonScene.useRightHandedSystem = true;
  530. break;
  531. default:
  532. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  533. return;
  534. }
  535. var nodeIndices = scene.nodes;
  536. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  537. node.parent = parentNode;
  538. return true;
  539. }, this._rootNode);
  540. if (nodeNames) {
  541. if (!(nodeNames instanceof Array)) {
  542. nodeNames = [nodeNames];
  543. }
  544. var filteredNodeIndices = new Array();
  545. this._traverseNodes(context, nodeIndices, function (node) {
  546. if (nodeNames.indexOf(node.name) !== -1) {
  547. filteredNodeIndices.push(node.index);
  548. return false;
  549. }
  550. return true;
  551. }, this._rootNode);
  552. nodeIndices = filteredNodeIndices;
  553. }
  554. for (var i = 0; i < nodeIndices.length; i++) {
  555. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, nodeIndices[i]);
  556. if (!node) {
  557. throw new Error(context + ": Failed to find node " + nodeIndices[i]);
  558. }
  559. this._loadNode("nodes[" + nodeIndices[i] + "]", node);
  560. }
  561. // Disable the root mesh until the asset is ready to render.
  562. this._rootNode.babylonMesh.setEnabled(false);
  563. };
  564. GLTFLoader.prototype._loadNode = function (context, node) {
  565. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  566. return;
  567. }
  568. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  569. this._loadTransform(node);
  570. if (node.mesh != null) {
  571. var mesh = GLTF2.GLTFUtils.GetArrayItem(this._gltf.meshes, node.mesh);
  572. if (!mesh) {
  573. throw new Error(context + ": Failed to find mesh " + node.mesh);
  574. }
  575. this._loadMesh("meshes[" + node.mesh + "]", node, mesh);
  576. }
  577. node.babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  578. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  579. node.babylonAnimationTargets.push(node.babylonMesh);
  580. if (node.skin != null) {
  581. var skin = GLTF2.GLTFUtils.GetArrayItem(this._gltf.skins, node.skin);
  582. if (!skin) {
  583. throw new Error(context + ": Failed to find skin " + node.skin);
  584. }
  585. node.babylonMesh.skeleton = this._loadSkin("skins[" + node.skin + "]", skin);
  586. }
  587. if (node.camera != null) {
  588. // TODO: handle cameras
  589. }
  590. if (node.children) {
  591. for (var i = 0; i < node.children.length; i++) {
  592. var childNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, node.children[i]);
  593. if (!childNode) {
  594. throw new Error(context + ": Failed to find child node " + node.children[i]);
  595. }
  596. this._loadNode("nodes[" + node.children[i] + "]", childNode);
  597. }
  598. }
  599. };
  600. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  601. node.babylonMesh.name = mesh.name || node.babylonMesh.name;
  602. var babylonMultiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  603. node.babylonMesh.material = babylonMultiMaterial;
  604. var geometry = new BABYLON.Geometry(node.babylonMesh.name, this._babylonScene, null, false, node.babylonMesh);
  605. var vertexData = new BABYLON.VertexData();
  606. vertexData.positions = [];
  607. vertexData.indices = [];
  608. var subMeshInfos = [];
  609. var numRemainingPrimitives = mesh.primitives.length;
  610. for (var index = 0; index < mesh.primitives.length; index++) {
  611. var primitive = mesh.primitives[index];
  612. this._loadPrimitive(context + "/primitives[" + index + "]", node, mesh, primitive, function (subVertexData, loadMaterial) {
  613. subMeshInfos.push({
  614. verticesStart: vertexData.positions.length,
  615. verticesCount: subVertexData.positions.length,
  616. indicesStart: vertexData.indices.length,
  617. indicesCount: subVertexData.indices.length,
  618. loadMaterial: loadMaterial
  619. });
  620. vertexData.merge(subVertexData);
  621. if (--numRemainingPrimitives === 0) {
  622. geometry.setAllVerticesData(vertexData, false);
  623. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  624. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  625. node.babylonMesh.subMeshes = [];
  626. for (var index = 0; index < subMeshInfos.length; index++) {
  627. var info = subMeshInfos[index];
  628. new BABYLON.SubMesh(index, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, node.babylonMesh);
  629. info.loadMaterial(index);
  630. }
  631. }
  632. });
  633. }
  634. };
  635. GLTFLoader.prototype._loadPrimitive = function (context, node, mesh, primitive, onSuccess) {
  636. var _this = this;
  637. var subMaterials = node.babylonMesh.material.subMaterials;
  638. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  639. // TODO: handle other primitive modes
  640. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  641. }
  642. this._createMorphTargets(node, mesh, primitive);
  643. this._loadVertexDataAsync(context, mesh, primitive, function (vertexData) {
  644. _this._loadMorphTargetsData(context, mesh, primitive, vertexData, node.babylonMesh);
  645. var loadMaterial = function (index) {
  646. if (primitive.material == null) {
  647. subMaterials[index] = _this._getDefaultMaterial();
  648. }
  649. else {
  650. var material = GLTF2.GLTFUtils.GetArrayItem(_this._gltf.materials, primitive.material);
  651. if (!material) {
  652. throw new Error(context + ": Failed to find material " + primitive.material);
  653. }
  654. _this._loadMaterial("materials[" + material.index + "]", material, function (babylonMaterial, isNew) {
  655. if (isNew && _this._parent.onMaterialLoaded) {
  656. _this._parent.onMaterialLoaded(babylonMaterial);
  657. }
  658. if (_this._parent.onBeforeMaterialReadyAsync) {
  659. _this._addLoaderPendingData(material);
  660. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, node.babylonMesh, subMaterials[index] != null, function () {
  661. subMaterials[index] = babylonMaterial;
  662. _this._removeLoaderPendingData(material);
  663. });
  664. }
  665. else {
  666. subMaterials[index] = babylonMaterial;
  667. }
  668. });
  669. }
  670. };
  671. onSuccess(vertexData, loadMaterial);
  672. });
  673. };
  674. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  675. var _this = this;
  676. var attributes = primitive.attributes;
  677. if (!attributes) {
  678. throw new Error(context + ": Attributes are missing");
  679. }
  680. var vertexData = new BABYLON.VertexData();
  681. var numRemainingAttributes = Object.keys(attributes).length;
  682. var _loop_1 = function (attribute) {
  683. accessor = GLTF2.GLTFUtils.GetArrayItem(this_1._gltf.accessors, attributes[attribute]);
  684. if (!accessor) {
  685. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  686. }
  687. this_1._loadAccessorAsync("accessors[" + accessor.index + "]", accessor, function (data) {
  688. switch (attribute) {
  689. case "NORMAL":
  690. vertexData.normals = data;
  691. break;
  692. case "POSITION":
  693. vertexData.positions = data;
  694. break;
  695. case "TANGENT":
  696. vertexData.tangents = data;
  697. break;
  698. case "TEXCOORD_0":
  699. vertexData.uvs = data;
  700. break;
  701. case "TEXCOORD_1":
  702. vertexData.uvs2 = data;
  703. break;
  704. case "JOINTS_0":
  705. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  706. break;
  707. case "WEIGHTS_0":
  708. vertexData.matricesWeights = data;
  709. break;
  710. case "COLOR_0":
  711. vertexData.colors = data;
  712. break;
  713. default:
  714. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  715. break;
  716. }
  717. if (--numRemainingAttributes === 0) {
  718. if (primitive.indices == null) {
  719. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  720. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  721. onSuccess(vertexData);
  722. }
  723. else {
  724. var indicesAccessor = GLTF2.GLTFUtils.GetArrayItem(_this._gltf.accessors, primitive.indices);
  725. if (!indicesAccessor) {
  726. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  727. }
  728. _this._loadAccessorAsync("accessors[" + indicesAccessor.index + "]", indicesAccessor, function (data) {
  729. vertexData.indices = data;
  730. onSuccess(vertexData);
  731. });
  732. }
  733. }
  734. });
  735. };
  736. var this_1 = this, accessor;
  737. for (var attribute in attributes) {
  738. _loop_1(attribute);
  739. }
  740. };
  741. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive) {
  742. var targets = primitive.targets;
  743. if (!targets) {
  744. return;
  745. }
  746. if (!node.babylonMesh.morphTargetManager) {
  747. node.babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  748. }
  749. for (var index = 0; index < targets.length; index++) {
  750. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  751. node.babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  752. }
  753. };
  754. GLTFLoader.prototype._loadMorphTargetsData = function (context, mesh, primitive, vertexData, babylonMesh) {
  755. var targets = primitive.targets;
  756. if (!targets) {
  757. return;
  758. }
  759. var _loop_2 = function () {
  760. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  761. attributes = targets[index];
  762. var _loop_3 = function (attribute) {
  763. accessor = GLTF2.GLTFUtils.GetArrayItem(this_2._gltf.accessors, attributes[attribute]);
  764. if (!accessor) {
  765. throw new Error(context + "/targets[" + index + "]: Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  766. }
  767. this_2._loadAccessorAsync("accessors[" + accessor.index + "]", accessor, function (data) {
  768. if (accessor.name) {
  769. babylonMorphTarget.name = accessor.name;
  770. }
  771. // glTF stores morph target information as deltas while babylon.js expects the final data.
  772. // As a result we have to add the original data to the delta to calculate the final data.
  773. var values = data;
  774. switch (attribute) {
  775. case "NORMAL":
  776. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.normals[i]; });
  777. babylonMorphTarget.setNormals(values);
  778. break;
  779. case "POSITION":
  780. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.positions[i]; });
  781. babylonMorphTarget.setPositions(values);
  782. break;
  783. case "TANGENT":
  784. // Tangent data for morph targets is stored as xyz delta.
  785. // The vertexData.tangent is stored as xyzw.
  786. // So we need to skip every fourth vertexData.tangent.
  787. for (var i = 0, j = 0; i < values.length; i++, j++) {
  788. values[i] += vertexData.tangents[j];
  789. if ((i + 1) % 3 == 0) {
  790. j++;
  791. }
  792. }
  793. babylonMorphTarget.setTangents(values);
  794. break;
  795. default:
  796. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  797. break;
  798. }
  799. });
  800. };
  801. for (var attribute in attributes) {
  802. _loop_3(attribute);
  803. }
  804. };
  805. var this_2 = this, attributes, accessor;
  806. for (var index = 0; index < targets.length; index++) {
  807. _loop_2();
  808. }
  809. };
  810. GLTFLoader.prototype._loadTransform = function (node) {
  811. var position = BABYLON.Vector3.Zero();
  812. var rotation = BABYLON.Quaternion.Identity();
  813. var scaling = BABYLON.Vector3.One();
  814. if (node.matrix) {
  815. var mat = BABYLON.Matrix.FromArray(node.matrix);
  816. mat.decompose(scaling, rotation, position);
  817. }
  818. else {
  819. if (node.translation)
  820. position = BABYLON.Vector3.FromArray(node.translation);
  821. if (node.rotation)
  822. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  823. if (node.scale)
  824. scaling = BABYLON.Vector3.FromArray(node.scale);
  825. }
  826. node.babylonMesh.position = position;
  827. node.babylonMesh.rotationQuaternion = rotation;
  828. node.babylonMesh.scaling = scaling;
  829. };
  830. GLTFLoader.prototype._loadSkin = function (context, skin) {
  831. var _this = this;
  832. var skeletonId = "skeleton" + skin.index;
  833. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  834. if (skin.inverseBindMatrices == null) {
  835. this._loadBones(context, skin, null);
  836. }
  837. else {
  838. var accessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, skin.inverseBindMatrices);
  839. if (!accessor) {
  840. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  841. }
  842. this._loadAccessorAsync("accessors[" + accessor.index + "]", accessor, function (data) {
  843. _this._loadBones(context, skin, data);
  844. });
  845. }
  846. return skin.babylonSkeleton;
  847. };
  848. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  849. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  850. node.babylonBones = node.babylonBones || {};
  851. node.babylonBones[skin.index] = babylonBone;
  852. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  853. node.babylonAnimationTargets.push(babylonBone);
  854. return babylonBone;
  855. };
  856. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  857. var babylonBones = {};
  858. for (var i = 0; i < skin.joints.length; i++) {
  859. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, skin.joints[i]);
  860. if (!node) {
  861. throw new Error(context + ": Failed to find joint " + skin.joints[i]);
  862. }
  863. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  864. }
  865. };
  866. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  867. var babylonBone = babylonBones[node.index];
  868. if (babylonBone) {
  869. return babylonBone;
  870. }
  871. var boneIndex = skin.joints.indexOf(node.index);
  872. var baseMatrix = BABYLON.Matrix.Identity();
  873. if (inverseBindMatrixData && boneIndex !== -1) {
  874. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  875. baseMatrix.invertToRef(baseMatrix);
  876. }
  877. var babylonParentBone;
  878. if (node.index !== skin.skeleton && node.parent !== this._rootNode) {
  879. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  880. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  881. }
  882. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  883. babylonBones[node.index] = babylonBone;
  884. return babylonBone;
  885. };
  886. GLTFLoader.prototype._getNodeMatrix = function (node) {
  887. return node.matrix ?
  888. BABYLON.Matrix.FromArray(node.matrix) :
  889. 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());
  890. };
  891. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  892. if (parentNode === void 0) { parentNode = null; }
  893. for (var i = 0; i < indices.length; i++) {
  894. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, indices[i]);
  895. if (!node) {
  896. throw new Error(context + ": Failed to find node " + indices[i]);
  897. }
  898. this._traverseNode(context, node, action, parentNode);
  899. }
  900. };
  901. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  902. if (parentNode === void 0) { parentNode = null; }
  903. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  904. return;
  905. }
  906. if (!action(node, parentNode)) {
  907. return;
  908. }
  909. if (node.children) {
  910. this._traverseNodes(context, node.children, action, node);
  911. }
  912. };
  913. GLTFLoader.prototype._loadAnimations = function () {
  914. var animations = this._gltf.animations;
  915. if (!animations) {
  916. return;
  917. }
  918. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  919. var animation = animations[animationIndex];
  920. var context = "animations[" + animationIndex + "]";
  921. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  922. var channel = GLTF2.GLTFUtils.GetArrayItem(animation.channels, channelIndex);
  923. if (!channel) {
  924. throw new Error(context + ": Failed to find channel " + channelIndex);
  925. }
  926. var sampler = GLTF2.GLTFUtils.GetArrayItem(animation.samplers, channel.sampler);
  927. if (!sampler) {
  928. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  929. }
  930. this._loadAnimationChannel(animation, context + "/channels[" + channelIndex + "]", channel, context + "/samplers[" + channel.sampler + "]", sampler);
  931. }
  932. }
  933. };
  934. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  935. var targetNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, channel.target.node);
  936. if (!targetNode) {
  937. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  938. }
  939. var conversion = {
  940. "translation": "position",
  941. "rotation": "rotationQuaternion",
  942. "scale": "scaling",
  943. "weights": "influence"
  944. };
  945. var targetPath = conversion[channel.target.path];
  946. if (!targetPath) {
  947. throw new Error(channelContext + ": Invalid target path '" + channel.target.path + "'");
  948. }
  949. var animationConvertion = {
  950. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  951. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  952. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  953. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  954. };
  955. var animationType = animationConvertion[targetPath];
  956. var inputData;
  957. var outputData;
  958. var checkSuccess = function () {
  959. if (!inputData || !outputData) {
  960. return;
  961. }
  962. var outputBufferOffset = 0;
  963. var nextOutputConversion = {
  964. "position": function () {
  965. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  966. outputBufferOffset += 3;
  967. return value;
  968. },
  969. "rotationQuaternion": function () {
  970. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  971. outputBufferOffset += 4;
  972. return value;
  973. },
  974. "scaling": function () {
  975. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  976. outputBufferOffset += 3;
  977. return value;
  978. },
  979. "influence": function () {
  980. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  981. var value = new Array(numTargets);
  982. for (var i = 0; i < numTargets; i++) {
  983. value[i] = outputData[outputBufferOffset++];
  984. }
  985. return value;
  986. },
  987. };
  988. var getNextOutputValue = nextOutputConversion[targetPath];
  989. var nextKeyConversion = {
  990. "LINEAR": function (frameIndex) { return ({
  991. frame: inputData[frameIndex],
  992. value: getNextOutputValue()
  993. }); },
  994. "CUBICSPLINE": function (frameIndex) { return ({
  995. frame: inputData[frameIndex],
  996. inTangent: getNextOutputValue(),
  997. value: getNextOutputValue(),
  998. outTangent: getNextOutputValue()
  999. }); },
  1000. };
  1001. var getNextKey = nextKeyConversion[sampler.interpolation];
  1002. if (!getNextKey) {
  1003. throw new Error(samplerContext + ": Invalid interpolation '" + sampler.interpolation + "'");
  1004. }
  1005. var keys = new Array(inputData.length);
  1006. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  1007. keys[frameIndex] = getNextKey(frameIndex);
  1008. }
  1009. animation.targets = animation.targets || [];
  1010. if (targetPath === "influence") {
  1011. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  1012. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  1013. var morphTarget = morphTargetManager.getTarget(targetIndex);
  1014. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  1015. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1016. babylonAnimation.setKeys(keys.map(function (key) { return ({
  1017. frame: key.frame,
  1018. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  1019. value: key.value[targetIndex],
  1020. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  1021. }); }));
  1022. morphTarget.animations.push(babylonAnimation);
  1023. animation.targets.push(morphTarget);
  1024. }
  1025. }
  1026. else {
  1027. var animationName = animation.name || "anim" + animation.index;
  1028. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1029. babylonAnimation.setKeys(keys);
  1030. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  1031. var target = targetNode.babylonAnimationTargets[i];
  1032. target.animations.push(babylonAnimation.clone());
  1033. animation.targets.push(target);
  1034. }
  1035. }
  1036. };
  1037. var inputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.input);
  1038. if (!inputAccessor) {
  1039. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  1040. }
  1041. this._loadAccessorAsync("accessors[" + inputAccessor.index + "]", inputAccessor, function (data) {
  1042. inputData = data;
  1043. checkSuccess();
  1044. });
  1045. var outputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.output);
  1046. if (!outputAccessor) {
  1047. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  1048. }
  1049. this._loadAccessorAsync("accessors[" + outputAccessor.index + "]", outputAccessor, function (data) {
  1050. outputData = data;
  1051. checkSuccess();
  1052. });
  1053. };
  1054. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  1055. var _this = this;
  1056. this._addPendingData(buffer);
  1057. if (buffer.loadedData) {
  1058. onSuccess(buffer.loadedData);
  1059. this._removePendingData(buffer);
  1060. }
  1061. else if (buffer.loadedObservable) {
  1062. buffer.loadedObservable.add(function (buffer) {
  1063. onSuccess(buffer.loadedData);
  1064. _this._removePendingData(buffer);
  1065. });
  1066. }
  1067. else {
  1068. if (!buffer.uri) {
  1069. throw new Error(context + ": Uri is missing");
  1070. }
  1071. if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  1072. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  1073. buffer.loadedData = new Uint8Array(data);
  1074. onSuccess(buffer.loadedData);
  1075. this._removePendingData(buffer);
  1076. }
  1077. else {
  1078. if (!GLTF2.GLTFUtils.ValidateUri(buffer.uri)) {
  1079. throw new Error(context + ": Uri '" + buffer.uri + "' is invalid");
  1080. }
  1081. buffer.loadedObservable = new BABYLON.Observable();
  1082. buffer.loadedObservable.add(function (buffer) {
  1083. onSuccess(buffer.loadedData);
  1084. _this._removePendingData(buffer);
  1085. });
  1086. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  1087. _this._tryCatchOnError(function () {
  1088. buffer.loadedData = new Uint8Array(data);
  1089. buffer.loadedObservable.notifyObservers(buffer);
  1090. buffer.loadedObservable = null;
  1091. });
  1092. }, function (event) {
  1093. _this._tryCatchOnError(function () {
  1094. _this._onProgress(event);
  1095. });
  1096. }, this._babylonScene.database, true, function (request) {
  1097. _this._tryCatchOnError(function () {
  1098. throw new Error(context + ": Failed to load '" + buffer.uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  1099. });
  1100. });
  1101. }
  1102. }
  1103. };
  1104. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  1105. var _this = this;
  1106. var buffer = GLTF2.GLTFUtils.GetArrayItem(this._gltf.buffers, bufferView.buffer);
  1107. if (!buffer) {
  1108. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  1109. }
  1110. this._loadBufferAsync("buffers[" + buffer.index + "]", buffer, function (bufferData) {
  1111. if (_this._disposed) {
  1112. return;
  1113. }
  1114. try {
  1115. var data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  1116. }
  1117. catch (e) {
  1118. throw new Error(context + ": " + e.message);
  1119. }
  1120. onSuccess(data);
  1121. });
  1122. };
  1123. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  1124. var _this = this;
  1125. if (accessor.sparse) {
  1126. throw new Error(context + ": Sparse accessors are not currently supported");
  1127. }
  1128. if (accessor.normalized) {
  1129. throw new Error(context + ": Normalized accessors are not currently supported");
  1130. }
  1131. var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, accessor.bufferView);
  1132. if (!bufferView) {
  1133. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  1134. }
  1135. this._loadBufferViewAsync("bufferViews[" + bufferView.index + "]", bufferView, function (bufferViewData) {
  1136. var numComponents = _this._getNumComponentsOfType(accessor.type);
  1137. if (numComponents === 0) {
  1138. throw new Error(context + ": Invalid type (" + accessor.type + ")");
  1139. }
  1140. var data;
  1141. switch (accessor.componentType) {
  1142. case GLTF2.EComponentType.BYTE:
  1143. data = _this._buildArrayBuffer(Float32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  1144. break;
  1145. case GLTF2.EComponentType.UNSIGNED_BYTE:
  1146. data = _this._buildArrayBuffer(Uint8Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  1147. break;
  1148. case GLTF2.EComponentType.SHORT:
  1149. data = _this._buildArrayBuffer(Int16Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  1150. break;
  1151. case GLTF2.EComponentType.UNSIGNED_SHORT:
  1152. data = _this._buildArrayBuffer(Uint16Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  1153. break;
  1154. case GLTF2.EComponentType.UNSIGNED_INT:
  1155. data = _this._buildArrayBuffer(Uint32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  1156. break;
  1157. case GLTF2.EComponentType.FLOAT:
  1158. data = _this._buildArrayBuffer(Float32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  1159. break;
  1160. default:
  1161. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  1162. }
  1163. onSuccess(data);
  1164. });
  1165. };
  1166. GLTFLoader.prototype._getNumComponentsOfType = function (type) {
  1167. switch (type) {
  1168. case "SCALAR": return 1;
  1169. case "VEC2": return 2;
  1170. case "VEC3": return 3;
  1171. case "VEC4": return 4;
  1172. case "MAT2": return 4;
  1173. case "MAT3": return 9;
  1174. case "MAT4": return 16;
  1175. }
  1176. return 0;
  1177. };
  1178. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, context, data, byteOffset, count, numComponents, byteStride) {
  1179. try {
  1180. var byteOffset = data.byteOffset + (byteOffset || 0);
  1181. var targetLength = count * numComponents;
  1182. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  1183. return new typedArray(data.buffer, byteOffset, targetLength);
  1184. }
  1185. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  1186. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  1187. var targetBuffer = new typedArray(targetLength);
  1188. var sourceIndex = 0;
  1189. var targetIndex = 0;
  1190. while (targetIndex < targetLength) {
  1191. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  1192. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  1193. targetIndex++;
  1194. }
  1195. sourceIndex += elementStride;
  1196. }
  1197. return targetBuffer;
  1198. }
  1199. catch (e) {
  1200. throw new Error(context + ": " + e);
  1201. }
  1202. };
  1203. GLTFLoader.prototype._addPendingData = function (data) {
  1204. if (!this._renderReady) {
  1205. this._renderPendingCount++;
  1206. }
  1207. this._addLoaderPendingData(data);
  1208. };
  1209. GLTFLoader.prototype._removePendingData = function (data) {
  1210. if (!this._renderReady) {
  1211. if (--this._renderPendingCount === 0) {
  1212. this._renderReady = true;
  1213. this._onRenderReady();
  1214. }
  1215. }
  1216. this._removeLoaderPendingData(data);
  1217. };
  1218. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  1219. this._loaderPendingCount++;
  1220. this._loaderTrackers.forEach(function (tracker) { return tracker._addPendingData(data); });
  1221. };
  1222. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  1223. this._loaderTrackers.forEach(function (tracker) { return tracker._removePendingData(data); });
  1224. if (--this._loaderPendingCount === 0) {
  1225. this._onComplete();
  1226. }
  1227. };
  1228. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  1229. var _this = this;
  1230. var tracker = new GLTFLoaderTracker(function () {
  1231. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker));
  1232. onComplete();
  1233. });
  1234. this._loaderTrackers.push(tracker);
  1235. this._addLoaderPendingData(tracker);
  1236. action();
  1237. this._removeLoaderPendingData(tracker);
  1238. };
  1239. GLTFLoader.prototype._getDefaultMaterial = function () {
  1240. if (!this._defaultMaterial) {
  1241. var id = "__gltf_default";
  1242. var material = this._babylonScene.getMaterialByName(id);
  1243. if (!material) {
  1244. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  1245. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1246. material.metallic = 1;
  1247. material.roughness = 1;
  1248. }
  1249. this._defaultMaterial = material;
  1250. }
  1251. return this._defaultMaterial;
  1252. };
  1253. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  1254. var babylonMaterial = material.babylonMaterial;
  1255. // Ensure metallic workflow
  1256. babylonMaterial.metallic = 1;
  1257. babylonMaterial.roughness = 1;
  1258. var properties = material.pbrMetallicRoughness;
  1259. if (!properties) {
  1260. return;
  1261. }
  1262. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  1263. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  1264. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  1265. if (properties.baseColorTexture) {
  1266. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.baseColorTexture.index);
  1267. if (!texture) {
  1268. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  1269. }
  1270. babylonMaterial.albedoTexture = this._loadTexture("textures[" + texture.index + "]", texture, properties.baseColorTexture.texCoord);
  1271. }
  1272. if (properties.metallicRoughnessTexture) {
  1273. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.metallicRoughnessTexture.index);
  1274. if (!texture) {
  1275. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  1276. }
  1277. babylonMaterial.metallicTexture = this._loadTexture("textures[" + texture.index + "]", texture, properties.metallicRoughnessTexture.texCoord);
  1278. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1279. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1280. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1281. }
  1282. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  1283. };
  1284. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  1285. if (material.babylonMaterial) {
  1286. assign(material.babylonMaterial, false);
  1287. return;
  1288. }
  1289. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  1290. return;
  1291. }
  1292. this._createPbrMaterial(material);
  1293. this._loadMaterialBaseProperties(context, material);
  1294. this._loadMaterialMetallicRoughnessProperties(context, material);
  1295. assign(material.babylonMaterial, true);
  1296. };
  1297. GLTFLoader.prototype._createPbrMaterial = function (material) {
  1298. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  1299. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1300. material.babylonMaterial = babylonMaterial;
  1301. };
  1302. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  1303. var babylonMaterial = material.babylonMaterial;
  1304. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  1305. if (material.doubleSided) {
  1306. babylonMaterial.backFaceCulling = false;
  1307. babylonMaterial.twoSidedLighting = true;
  1308. }
  1309. if (material.normalTexture) {
  1310. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.normalTexture.index);
  1311. if (!texture) {
  1312. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  1313. }
  1314. babylonMaterial.bumpTexture = this._loadTexture("textures[" + texture.index + "]", texture, material.normalTexture.texCoord);
  1315. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  1316. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  1317. if (material.normalTexture.scale != null) {
  1318. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1319. }
  1320. }
  1321. if (material.occlusionTexture) {
  1322. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.occlusionTexture.index);
  1323. if (!texture) {
  1324. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  1325. }
  1326. babylonMaterial.ambientTexture = this._loadTexture("textures[" + texture.index + "]", texture, material.occlusionTexture.texCoord);
  1327. babylonMaterial.useAmbientInGrayScale = true;
  1328. if (material.occlusionTexture.strength != null) {
  1329. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1330. }
  1331. }
  1332. if (material.emissiveTexture) {
  1333. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.emissiveTexture.index);
  1334. if (!texture) {
  1335. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  1336. }
  1337. babylonMaterial.emissiveTexture = this._loadTexture("textures[" + texture.index + "]", texture, material.emissiveTexture.texCoord);
  1338. }
  1339. };
  1340. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  1341. var babylonMaterial = material.babylonMaterial;
  1342. var alphaMode = material.alphaMode || "OPAQUE";
  1343. switch (alphaMode) {
  1344. case "OPAQUE":
  1345. // default is opaque
  1346. break;
  1347. case "MASK":
  1348. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  1349. if (colorFactor) {
  1350. if (colorFactor[3] == 0) {
  1351. babylonMaterial.alphaCutOff = 1;
  1352. }
  1353. else {
  1354. babylonMaterial.alphaCutOff /= colorFactor[3];
  1355. }
  1356. }
  1357. if (babylonMaterial.albedoTexture) {
  1358. babylonMaterial.albedoTexture.hasAlpha = true;
  1359. }
  1360. break;
  1361. case "BLEND":
  1362. if (colorFactor) {
  1363. babylonMaterial.alpha = colorFactor[3];
  1364. }
  1365. if (babylonMaterial.albedoTexture) {
  1366. babylonMaterial.albedoTexture.hasAlpha = true;
  1367. babylonMaterial.useAlphaFromAlbedoTexture = true;
  1368. }
  1369. break;
  1370. default:
  1371. throw new Error(context + ": Invalid alpha mode '" + material.alphaMode + "'");
  1372. }
  1373. };
  1374. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  1375. var _this = this;
  1376. var sampler = (texture.sampler == null ? {} : GLTF2.GLTFUtils.GetArrayItem(this._gltf.samplers, texture.sampler));
  1377. if (!sampler) {
  1378. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  1379. }
  1380. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  1381. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  1382. this._addPendingData(texture);
  1383. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  1384. _this._tryCatchOnError(function () {
  1385. _this._removePendingData(texture);
  1386. });
  1387. }, function (message) {
  1388. _this._tryCatchOnError(function () {
  1389. throw new Error(context + ": " + message);
  1390. });
  1391. });
  1392. if (texture.url) {
  1393. babylonTexture.updateURL(texture.url);
  1394. }
  1395. else if (texture.dataReadyObservable) {
  1396. texture.dataReadyObservable.add(function (texture) {
  1397. babylonTexture.updateURL(texture.url);
  1398. });
  1399. }
  1400. else {
  1401. texture.dataReadyObservable = new BABYLON.Observable();
  1402. texture.dataReadyObservable.add(function (texture) {
  1403. babylonTexture.updateURL(texture.url);
  1404. });
  1405. var image = GLTF2.GLTFUtils.GetArrayItem(this._gltf.images, texture.source);
  1406. if (!image) {
  1407. throw new Error(context + ": Failed to find source " + texture.source);
  1408. }
  1409. this._loadImage("images[" + image.index + "]", image, function (data) {
  1410. texture.url = URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  1411. texture.dataReadyObservable.notifyObservers(texture);
  1412. });
  1413. }
  1414. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  1415. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  1416. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  1417. babylonTexture.name = texture.name || "texture" + texture.index;
  1418. if (this._parent.onTextureLoaded) {
  1419. this._parent.onTextureLoaded(babylonTexture);
  1420. }
  1421. return babylonTexture;
  1422. };
  1423. GLTFLoader.prototype._loadImage = function (context, image, onSuccess) {
  1424. var _this = this;
  1425. if (image.uri) {
  1426. if (!GLTF2.GLTFUtils.ValidateUri(image.uri)) {
  1427. throw new Error(context + ": Uri '" + image.uri + "' is invalid");
  1428. }
  1429. if (GLTF2.GLTFUtils.IsBase64(image.uri)) {
  1430. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(image.uri)));
  1431. }
  1432. else {
  1433. BABYLON.Tools.LoadFile(this._rootUrl + image.uri, function (data) {
  1434. _this._tryCatchOnError(function () {
  1435. onSuccess(data);
  1436. });
  1437. }, function (event) {
  1438. _this._tryCatchOnError(function () {
  1439. _this._onProgress(event);
  1440. });
  1441. }, this._babylonScene.database, true, function (request) {
  1442. _this._tryCatchOnError(function () {
  1443. throw new Error(context + ": Failed to load '" + image.uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  1444. });
  1445. });
  1446. }
  1447. }
  1448. else {
  1449. var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, image.bufferView);
  1450. if (!bufferView) {
  1451. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  1452. }
  1453. this._loadBufferViewAsync("bufferViews[" + bufferView.index + "]", bufferView, onSuccess);
  1454. }
  1455. };
  1456. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  1457. try {
  1458. handler();
  1459. }
  1460. catch (e) {
  1461. this._onError(e.message);
  1462. }
  1463. };
  1464. GLTFLoader.Extensions = {};
  1465. return GLTFLoader;
  1466. }());
  1467. GLTF2.GLTFLoader = GLTFLoader;
  1468. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  1469. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1470. })(BABYLON || (BABYLON = {}));
  1471. //# sourceMappingURL=babylon.glTFLoader.js.map
  1472. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1473. var BABYLON;
  1474. (function (BABYLON) {
  1475. var GLTF2;
  1476. (function (GLTF2) {
  1477. /**
  1478. * Utils functions for GLTF
  1479. */
  1480. var GLTFUtils = (function () {
  1481. function GLTFUtils() {
  1482. }
  1483. /**
  1484. * If the uri is a base64 string
  1485. * @param uri: the uri to test
  1486. */
  1487. GLTFUtils.IsBase64 = function (uri) {
  1488. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1489. };
  1490. /**
  1491. * Decode the base64 uri
  1492. * @param uri: the uri to decode
  1493. */
  1494. GLTFUtils.DecodeBase64 = function (uri) {
  1495. var decodedString = atob(uri.split(",")[1]);
  1496. var bufferLength = decodedString.length;
  1497. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1498. for (var i = 0; i < bufferLength; i++) {
  1499. bufferView[i] = decodedString.charCodeAt(i);
  1500. }
  1501. return bufferView.buffer;
  1502. };
  1503. GLTFUtils.ForEach = function (view, func) {
  1504. for (var index = 0; index < view.length; index++) {
  1505. func(view[index], index);
  1506. }
  1507. };
  1508. GLTFUtils.ValidateUri = function (uri) {
  1509. return (uri.indexOf("..") === -1);
  1510. };
  1511. GLTFUtils.AssignIndices = function (array) {
  1512. if (array) {
  1513. for (var index = 0; index < array.length; index++) {
  1514. array[index].index = index;
  1515. }
  1516. }
  1517. };
  1518. GLTFUtils.GetArrayItem = function (array, index) {
  1519. if (!array || !array[index]) {
  1520. return null;
  1521. }
  1522. return array[index];
  1523. };
  1524. GLTFUtils.GetTextureWrapMode = function (mode) {
  1525. // Set defaults if undefined
  1526. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  1527. switch (mode) {
  1528. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1529. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1530. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1531. default:
  1532. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  1533. return BABYLON.Texture.WRAP_ADDRESSMODE;
  1534. }
  1535. };
  1536. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  1537. // Set defaults if undefined
  1538. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  1539. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  1540. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  1541. switch (minFilter) {
  1542. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  1543. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  1544. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  1545. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  1546. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  1547. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  1548. default:
  1549. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  1550. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  1551. }
  1552. }
  1553. else {
  1554. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  1555. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  1556. }
  1557. switch (minFilter) {
  1558. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  1559. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  1560. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  1561. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  1562. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  1563. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  1564. default:
  1565. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  1566. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  1567. }
  1568. }
  1569. };
  1570. /**
  1571. * Decodes a buffer view into a string
  1572. * @param view: the buffer view
  1573. */
  1574. GLTFUtils.DecodeBufferToText = function (view) {
  1575. var result = "";
  1576. var length = view.byteLength;
  1577. for (var i = 0; i < length; ++i) {
  1578. result += String.fromCharCode(view[i]);
  1579. }
  1580. return result;
  1581. };
  1582. return GLTFUtils;
  1583. }());
  1584. GLTF2.GLTFUtils = GLTFUtils;
  1585. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1586. })(BABYLON || (BABYLON = {}));
  1587. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  1588. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1589. var BABYLON;
  1590. (function (BABYLON) {
  1591. var GLTF2;
  1592. (function (GLTF2) {
  1593. var GLTFLoaderExtension = (function () {
  1594. function GLTFLoaderExtension() {
  1595. this.enabled = true;
  1596. }
  1597. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  1598. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  1599. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  1600. GLTFLoaderExtension.prototype._loadExtension = function (property, action) {
  1601. var _this = this;
  1602. if (!property.extensions) {
  1603. return false;
  1604. }
  1605. var extension = property.extensions[this.name];
  1606. if (!extension) {
  1607. return false;
  1608. }
  1609. // Clear out the extension before executing the action to avoid recursing into the same property.
  1610. property.extensions[this.name] = undefined;
  1611. action(extension, function () {
  1612. // Restore the extension after completing the action.
  1613. property.extensions[_this.name] = extension;
  1614. });
  1615. return true;
  1616. };
  1617. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  1618. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  1619. };
  1620. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  1621. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  1622. };
  1623. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  1624. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  1625. };
  1626. GLTFLoaderExtension._ApplyExtensions = function (action) {
  1627. var extensions = GLTFLoaderExtension._Extensions;
  1628. if (!extensions) {
  1629. return;
  1630. }
  1631. for (var i = 0; i < extensions.length; i++) {
  1632. var extension = extensions[i];
  1633. if (extension.enabled && action(extension)) {
  1634. return true;
  1635. }
  1636. }
  1637. return false;
  1638. };
  1639. //
  1640. // Utilities
  1641. //
  1642. GLTFLoaderExtension._Extensions = [];
  1643. return GLTFLoaderExtension;
  1644. }());
  1645. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  1646. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1647. })(BABYLON || (BABYLON = {}));
  1648. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  1649. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  1650. var __extends = (this && this.__extends) || (function () {
  1651. var extendStatics = Object.setPrototypeOf ||
  1652. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1653. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1654. return function (d, b) {
  1655. extendStatics(d, b);
  1656. function __() { this.constructor = d; }
  1657. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1658. };
  1659. })();
  1660. var BABYLON;
  1661. (function (BABYLON) {
  1662. var GLTF2;
  1663. (function (GLTF2) {
  1664. var Extensions;
  1665. (function (Extensions) {
  1666. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  1667. var MSFTLOD = (function (_super) {
  1668. __extends(MSFTLOD, _super);
  1669. function MSFTLOD() {
  1670. return _super !== null && _super.apply(this, arguments) || this;
  1671. }
  1672. Object.defineProperty(MSFTLOD.prototype, "name", {
  1673. get: function () {
  1674. return "MSFT_lod";
  1675. },
  1676. enumerable: true,
  1677. configurable: true
  1678. });
  1679. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  1680. return this._loadExtension(node, function (extension, onComplete) {
  1681. for (var i = extension.ids.length - 1; i >= 0; i--) {
  1682. var lodNode = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.nodes, extension.ids[i]);
  1683. if (!lodNode) {
  1684. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  1685. }
  1686. loader._traverseNode(context, lodNode, action, parentNode);
  1687. }
  1688. loader._traverseNode(context, node, action, parentNode);
  1689. onComplete();
  1690. });
  1691. };
  1692. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  1693. var _this = this;
  1694. return this._loadExtension(node, function (extension, onComplete) {
  1695. var nodes = [node.index].concat(extension.ids).map(function (index) { return loader._gltf.nodes[index]; });
  1696. loader._addLoaderPendingData(node);
  1697. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  1698. loader._removeLoaderPendingData(node);
  1699. onComplete();
  1700. });
  1701. });
  1702. };
  1703. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  1704. var _this = this;
  1705. loader._whenAction(function () {
  1706. loader._loadNode(context, nodes[index]);
  1707. }, function () {
  1708. if (index !== nodes.length - 1) {
  1709. var previousNode = nodes[index + 1];
  1710. previousNode.babylonMesh.setEnabled(false);
  1711. }
  1712. if (index === 0) {
  1713. onComplete();
  1714. return;
  1715. }
  1716. setTimeout(function () {
  1717. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  1718. }, MSFTLOD.MinimalLODDelay);
  1719. });
  1720. };
  1721. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  1722. var _this = this;
  1723. return this._loadExtension(material, function (extension, onComplete) {
  1724. var materials = [material.index].concat(extension.ids).map(function (index) { return loader._gltf.materials[index]; });
  1725. loader._addLoaderPendingData(material);
  1726. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  1727. material.extensions[_this.name] = extension;
  1728. loader._removeLoaderPendingData(material);
  1729. onComplete();
  1730. });
  1731. });
  1732. };
  1733. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  1734. var _this = this;
  1735. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  1736. assign(babylonMaterial, isNew);
  1737. if (index === 0) {
  1738. onComplete();
  1739. return;
  1740. }
  1741. // Load the next LOD when the loader is ready to render and
  1742. // all active material textures of the current LOD are loaded.
  1743. loader._executeWhenRenderReady(function () {
  1744. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  1745. setTimeout(function () {
  1746. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  1747. }, MSFTLOD.MinimalLODDelay);
  1748. });
  1749. });
  1750. });
  1751. };
  1752. /**
  1753. * Specify the minimal delay between LODs in ms (default = 250)
  1754. */
  1755. MSFTLOD.MinimalLODDelay = 250;
  1756. return MSFTLOD;
  1757. }(GLTF2.GLTFLoaderExtension));
  1758. Extensions.MSFTLOD = MSFTLOD;
  1759. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  1760. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  1761. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1762. })(BABYLON || (BABYLON = {}));
  1763. //# sourceMappingURL=MSFT_lod.js.map
  1764. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  1765. var __extends = (this && this.__extends) || (function () {
  1766. var extendStatics = Object.setPrototypeOf ||
  1767. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1768. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1769. return function (d, b) {
  1770. extendStatics(d, b);
  1771. function __() { this.constructor = d; }
  1772. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1773. };
  1774. })();
  1775. var BABYLON;
  1776. (function (BABYLON) {
  1777. var GLTF2;
  1778. (function (GLTF2) {
  1779. var Extensions;
  1780. (function (Extensions) {
  1781. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  1782. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  1783. function KHRMaterialsPbrSpecularGlossiness() {
  1784. return _super !== null && _super.apply(this, arguments) || this;
  1785. }
  1786. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  1787. get: function () {
  1788. return "KHR_materials_pbrSpecularGlossiness";
  1789. },
  1790. enumerable: true,
  1791. configurable: true
  1792. });
  1793. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  1794. var _this = this;
  1795. return this._loadExtension(material, function (extension, onComplete) {
  1796. loader._createPbrMaterial(material);
  1797. loader._loadMaterialBaseProperties(context, material);
  1798. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  1799. assign(material.babylonMaterial, true);
  1800. });
  1801. };
  1802. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  1803. var babylonMaterial = material.babylonMaterial;
  1804. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  1805. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  1806. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  1807. if (properties.diffuseTexture) {
  1808. var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.diffuseTexture.index);
  1809. if (!texture) {
  1810. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  1811. }
  1812. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  1813. }
  1814. if (properties.specularGlossinessTexture) {
  1815. var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.specularGlossinessTexture.index);
  1816. if (!texture) {
  1817. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  1818. }
  1819. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  1820. babylonMaterial.reflectivityTexture.hasAlpha = true;
  1821. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  1822. }
  1823. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  1824. };
  1825. return KHRMaterialsPbrSpecularGlossiness;
  1826. }(GLTF2.GLTFLoaderExtension));
  1827. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  1828. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  1829. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  1830. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1831. })(BABYLON || (BABYLON = {}));
  1832. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map