babylon.glTF2FileLoader.js 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686
  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. if (data instanceof ArrayBuffer) {
  57. return GLTFFileLoader._parseBinary(data, onError);
  58. }
  59. try {
  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 GLTFLoader = (function () {
  320. function GLTFLoader(parent) {
  321. this._renderReady = false;
  322. this._disposed = false;
  323. this._blockPendingTracking = false;
  324. // Observable with boolean indicating success or error.
  325. this._renderReadyObservable = new BABYLON.Observable();
  326. // Count of pending work that needs to complete before the asset is rendered.
  327. this._renderPendingCount = 0;
  328. // Count of pending work that needs to complete before the loader is cleared.
  329. this._loaderPendingCount = 0;
  330. this._parent = parent;
  331. }
  332. GLTFLoader.RegisterExtension = function (extension) {
  333. if (GLTFLoader.Extensions[extension.name]) {
  334. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  335. return;
  336. }
  337. GLTFLoader.Extensions[extension.name] = extension;
  338. // Keep the order of registration so that extensions registered first are called first.
  339. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  340. };
  341. Object.defineProperty(GLTFLoader.prototype, "gltf", {
  342. get: function () {
  343. return this._gltf;
  344. },
  345. enumerable: true,
  346. configurable: true
  347. });
  348. Object.defineProperty(GLTFLoader.prototype, "babylonScene", {
  349. get: function () {
  350. return this._babylonScene;
  351. },
  352. enumerable: true,
  353. configurable: true
  354. });
  355. GLTFLoader.prototype.executeWhenRenderReady = function (func) {
  356. if (this._renderReady) {
  357. func();
  358. }
  359. else {
  360. this._renderReadyObservable.add(func);
  361. }
  362. };
  363. GLTFLoader.prototype.dispose = function () {
  364. if (this._disposed) {
  365. return;
  366. }
  367. this._disposed = true;
  368. // Revoke object urls created during load
  369. if (this._gltf.textures) {
  370. this._gltf.textures.forEach(function (texture) {
  371. if (texture.url) {
  372. URL.revokeObjectURL(texture.url);
  373. }
  374. });
  375. }
  376. this._gltf = undefined;
  377. this._babylonScene = undefined;
  378. this._rootUrl = undefined;
  379. this._defaultMaterial = undefined;
  380. this._successCallback = undefined;
  381. this._errorCallback = undefined;
  382. this._renderReady = false;
  383. this._renderReadyObservable.clear();
  384. this._renderPendingCount = 0;
  385. this._loaderPendingCount = 0;
  386. };
  387. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  388. var _this = this;
  389. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  390. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  391. }, onProgress, onError);
  392. };
  393. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  394. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  395. };
  396. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  397. this._loadData(data);
  398. this._babylonScene = scene;
  399. this._rootUrl = rootUrl;
  400. this._successCallback = onSuccess;
  401. this._progressCallback = onProgress;
  402. this._errorCallback = onError;
  403. this.addPendingData(this);
  404. this._loadScene(nodeNames);
  405. this._loadAnimations();
  406. this.removePendingData(this);
  407. };
  408. GLTFLoader.prototype._onError = function (message) {
  409. if (this._errorCallback) {
  410. this._errorCallback(message);
  411. }
  412. this.dispose();
  413. };
  414. GLTFLoader.prototype._onProgress = function (event) {
  415. this._progressCallback(event);
  416. };
  417. GLTFLoader.prototype._onRenderReady = function () {
  418. switch (this._parent.coordinateSystemMode) {
  419. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  420. if (!this._babylonScene.useRightHandedSystem) {
  421. this._addRightHandToLeftHandRootTransform();
  422. }
  423. break;
  424. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  425. // do nothing
  426. break;
  427. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  428. this._babylonScene.useRightHandedSystem = true;
  429. break;
  430. default:
  431. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  432. break;
  433. }
  434. this._showMeshes();
  435. this._startAnimations();
  436. this._successCallback();
  437. this._renderReadyObservable.notifyObservers(this);
  438. };
  439. GLTFLoader.prototype._onLoaderComplete = function () {
  440. if (this._parent.onComplete) {
  441. this._parent.onComplete();
  442. }
  443. };
  444. GLTFLoader.prototype._onLoaderFirstLODComplete = function () {
  445. if (this._parent.onFirstLODComplete) {
  446. this._parent.onFirstLODComplete();
  447. }
  448. };
  449. GLTFLoader.prototype._loadData = function (data) {
  450. this._gltf = data.json;
  451. var binaryBuffer;
  452. var buffers = this._gltf.buffers;
  453. if (buffers && buffers[0].uri === undefined) {
  454. binaryBuffer = buffers[0];
  455. }
  456. if (data.bin) {
  457. if (binaryBuffer) {
  458. if (binaryBuffer.byteLength != data.bin.byteLength) {
  459. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  460. }
  461. }
  462. else {
  463. BABYLON.Tools.Warn("Unexpected BIN chunk");
  464. }
  465. binaryBuffer.loadedData = data.bin;
  466. }
  467. };
  468. GLTFLoader.prototype._addRightHandToLeftHandRootTransform = function () {
  469. this._rootMesh = new BABYLON.Mesh("root", this._babylonScene);
  470. this._rootMesh.isVisible = false;
  471. this._rootMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  472. this._rootMesh.rotation.y = Math.PI;
  473. var nodes = this._gltf.nodes;
  474. if (nodes) {
  475. for (var i = 0; i < nodes.length; i++) {
  476. var mesh = nodes[i].babylonMesh;
  477. if (mesh && !mesh.parent) {
  478. mesh.parent = this._rootMesh;
  479. }
  480. }
  481. }
  482. };
  483. GLTFLoader.prototype._getMeshes = function () {
  484. var meshes = [];
  485. if (this._rootMesh) {
  486. meshes.push(this._rootMesh);
  487. }
  488. var nodes = this._gltf.nodes;
  489. if (nodes) {
  490. nodes.forEach(function (node) {
  491. if (node.babylonMesh) {
  492. meshes.push(node.babylonMesh);
  493. }
  494. });
  495. }
  496. return meshes;
  497. };
  498. GLTFLoader.prototype._getSkeletons = function () {
  499. var skeletons = [];
  500. var skins = this._gltf.skins;
  501. if (skins) {
  502. skins.forEach(function (skin) {
  503. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  504. skeletons.push(skin.babylonSkeleton);
  505. }
  506. });
  507. }
  508. return skeletons;
  509. };
  510. GLTFLoader.prototype._getAnimationTargets = function () {
  511. var targets = [];
  512. var animations = this._gltf.animations;
  513. if (animations) {
  514. animations.forEach(function (animation) {
  515. targets.push.apply(targets, animation.targets);
  516. });
  517. }
  518. return targets;
  519. };
  520. GLTFLoader.prototype._showMeshes = function () {
  521. this._getMeshes().forEach(function (mesh) { return mesh.isVisible = true; });
  522. };
  523. GLTFLoader.prototype._startAnimations = function () {
  524. var _this = this;
  525. this._getAnimationTargets().forEach(function (target) { return _this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); });
  526. };
  527. GLTFLoader.prototype._loadScene = function (nodeNames) {
  528. var _this = this;
  529. var scene = this._gltf.scenes[this._gltf.scene || 0];
  530. var nodeIndices = scene.nodes;
  531. this._traverseNodes(nodeIndices, function (node, index, parentNode) {
  532. node.index = index;
  533. node.parent = parentNode;
  534. return true;
  535. });
  536. var materials = this._gltf.materials;
  537. if (materials) {
  538. materials.forEach(function (material, index) { return material.index = index; });
  539. }
  540. if (nodeNames) {
  541. if (!(nodeNames instanceof Array)) {
  542. nodeNames = [nodeNames];
  543. }
  544. var filteredNodeIndices = new Array();
  545. this._traverseNodes(nodeIndices, function (node) {
  546. if (nodeNames.indexOf(node.name) === -1) {
  547. return true;
  548. }
  549. filteredNodeIndices.push(node.index);
  550. return false;
  551. });
  552. nodeIndices = filteredNodeIndices;
  553. }
  554. this._traverseNodes(nodeIndices, function (node) { return _this._loadNode(node); });
  555. };
  556. GLTFLoader.prototype._loadNode = function (node) {
  557. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  558. node.babylonMesh.isVisible = false;
  559. this._loadTransform(node);
  560. if (node.mesh !== undefined) {
  561. var mesh = this._gltf.meshes[node.mesh];
  562. this._loadMesh(node, mesh);
  563. }
  564. node.babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  565. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  566. node.babylonAnimationTargets.push(node.babylonMesh);
  567. if (node.skin !== undefined) {
  568. var skin = this._gltf.skins[node.skin];
  569. skin.index = node.skin;
  570. node.babylonMesh.skeleton = this._loadSkin(skin);
  571. }
  572. if (node.camera !== undefined) {
  573. // TODO: handle cameras
  574. }
  575. return true;
  576. };
  577. GLTFLoader.prototype._loadMesh = function (node, mesh) {
  578. var _this = this;
  579. node.babylonMesh.name = mesh.name || node.babylonMesh.name;
  580. var babylonMultiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  581. node.babylonMesh.material = babylonMultiMaterial;
  582. var geometry = new BABYLON.Geometry(node.babylonMesh.name, this._babylonScene, null, false, node.babylonMesh);
  583. var vertexData = new BABYLON.VertexData();
  584. vertexData.positions = [];
  585. vertexData.indices = [];
  586. var subMeshInfos = [];
  587. var loadedPrimitives = 0;
  588. var totalPrimitives = mesh.primitives.length;
  589. var _loop_1 = function (i) {
  590. var primitive = mesh.primitives[i];
  591. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  592. // TODO: handle other primitive modes
  593. throw new Error("Not implemented");
  594. }
  595. this_1._createMorphTargets(node, mesh, primitive, node.babylonMesh);
  596. this_1._loadVertexDataAsync(primitive, function (subVertexData) {
  597. _this._loadMorphTargetsData(mesh, primitive, subVertexData, node.babylonMesh);
  598. subMeshInfos.push({
  599. materialIndex: i,
  600. verticesStart: vertexData.positions.length,
  601. verticesCount: subVertexData.positions.length,
  602. indicesStart: vertexData.indices.length,
  603. indicesCount: subVertexData.indices.length,
  604. loadMaterial: function () {
  605. if (primitive.material === undefined) {
  606. babylonMultiMaterial.subMaterials[i] = _this._getDefaultMaterial();
  607. }
  608. else {
  609. var material = _this._gltf.materials[primitive.material];
  610. _this.loadMaterial(material, function (babylonMaterial, isNew) {
  611. if (isNew && _this._parent.onMaterialLoaded) {
  612. _this._parent.onMaterialLoaded(babylonMaterial);
  613. }
  614. if (_this._parent.onBeforeMaterialReadyAsync) {
  615. _this.addLoaderPendingData(material);
  616. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, node.babylonMesh, babylonMultiMaterial.subMaterials[i] != null, function () {
  617. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  618. _this.removeLoaderPendingData(material);
  619. });
  620. }
  621. else {
  622. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  623. }
  624. });
  625. }
  626. }
  627. });
  628. vertexData.merge(subVertexData);
  629. if (++loadedPrimitives === totalPrimitives) {
  630. geometry.setAllVerticesData(vertexData, false);
  631. subMeshInfos.forEach(function (info) { return info.loadMaterial(); });
  632. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  633. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  634. node.babylonMesh.subMeshes = [];
  635. subMeshInfos.forEach(function (info) { return new BABYLON.SubMesh(info.materialIndex, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, node.babylonMesh); });
  636. }
  637. });
  638. };
  639. var this_1 = this;
  640. for (var i = 0; i < totalPrimitives; i++) {
  641. _loop_1(i);
  642. }
  643. };
  644. GLTFLoader.prototype._loadVertexDataAsync = function (primitive, onSuccess) {
  645. var _this = this;
  646. var attributes = primitive.attributes;
  647. if (!attributes) {
  648. this._onError("Primitive has no attributes");
  649. return;
  650. }
  651. var vertexData = new BABYLON.VertexData();
  652. var loadedAttributes = 0;
  653. var totalAttributes = Object.keys(attributes).length;
  654. var _loop_2 = function (semantic) {
  655. accessor = this_2._gltf.accessors[attributes[semantic]];
  656. this_2._loadAccessorAsync(accessor, function (data) {
  657. switch (semantic) {
  658. case "NORMAL":
  659. vertexData.normals = data;
  660. break;
  661. case "POSITION":
  662. vertexData.positions = data;
  663. break;
  664. case "TANGENT":
  665. vertexData.tangents = data;
  666. break;
  667. case "TEXCOORD_0":
  668. vertexData.uvs = data;
  669. break;
  670. case "TEXCOORD_1":
  671. vertexData.uvs2 = data;
  672. break;
  673. case "JOINTS_0":
  674. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  675. break;
  676. case "WEIGHTS_0":
  677. vertexData.matricesWeights = data;
  678. break;
  679. case "COLOR_0":
  680. vertexData.colors = data;
  681. break;
  682. default:
  683. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  684. break;
  685. }
  686. if (++loadedAttributes === totalAttributes) {
  687. var indicesAccessor = _this._gltf.accessors[primitive.indices];
  688. if (indicesAccessor) {
  689. _this._loadAccessorAsync(indicesAccessor, function (data) {
  690. vertexData.indices = data;
  691. onSuccess(vertexData);
  692. });
  693. }
  694. else {
  695. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  696. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  697. onSuccess(vertexData);
  698. }
  699. }
  700. });
  701. };
  702. var this_2 = this, accessor;
  703. for (var semantic in attributes) {
  704. _loop_2(semantic);
  705. }
  706. };
  707. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive, babylonMesh) {
  708. var targets = primitive.targets;
  709. if (!targets) {
  710. return;
  711. }
  712. if (!babylonMesh.morphTargetManager) {
  713. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  714. }
  715. for (var index = 0; index < targets.length; index++) {
  716. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  717. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  718. }
  719. };
  720. GLTFLoader.prototype._loadMorphTargetsData = function (mesh, primitive, vertexData, babylonMesh) {
  721. var targets = primitive.targets;
  722. if (!targets) {
  723. return;
  724. }
  725. var _loop_3 = function () {
  726. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  727. attributes = targets[index];
  728. var _loop_4 = function (semantic) {
  729. accessor = this_3._gltf.accessors[attributes[semantic]];
  730. this_3._loadAccessorAsync(accessor, function (data) {
  731. if (accessor.name) {
  732. babylonMorphTarget.name = accessor.name;
  733. }
  734. // glTF stores morph target information as deltas while babylon.js expects the final data.
  735. // As a result we have to add the original data to the delta to calculate the final data.
  736. var values = data;
  737. switch (semantic) {
  738. case "NORMAL":
  739. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.normals[i]; });
  740. babylonMorphTarget.setNormals(values);
  741. break;
  742. case "POSITION":
  743. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.positions[i]; });
  744. babylonMorphTarget.setPositions(values);
  745. break;
  746. case "TANGENT":
  747. // Tangent data for morph targets is stored as xyz delta.
  748. // The vertexData.tangent is stored as xyzw.
  749. // So we need to skip every fourth vertexData.tangent.
  750. for (var i = 0, j = 0; i < values.length; i++, j++) {
  751. values[i] += vertexData.tangents[j];
  752. if ((i + 1) % 3 == 0) {
  753. j++;
  754. }
  755. }
  756. babylonMorphTarget.setTangents(values);
  757. break;
  758. default:
  759. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  760. break;
  761. }
  762. });
  763. };
  764. for (var semantic in attributes) {
  765. _loop_4(semantic);
  766. }
  767. };
  768. var this_3 = this, attributes, accessor;
  769. for (var index = 0; index < targets.length; index++) {
  770. _loop_3();
  771. }
  772. };
  773. GLTFLoader.prototype._loadTransform = function (node) {
  774. var position = BABYLON.Vector3.Zero();
  775. var rotation = BABYLON.Quaternion.Identity();
  776. var scaling = BABYLON.Vector3.One();
  777. if (node.matrix) {
  778. var mat = BABYLON.Matrix.FromArray(node.matrix);
  779. mat.decompose(scaling, rotation, position);
  780. }
  781. else {
  782. if (node.translation)
  783. position = BABYLON.Vector3.FromArray(node.translation);
  784. if (node.rotation)
  785. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  786. if (node.scale)
  787. scaling = BABYLON.Vector3.FromArray(node.scale);
  788. }
  789. node.babylonMesh.position = position;
  790. node.babylonMesh.rotationQuaternion = rotation;
  791. node.babylonMesh.scaling = scaling;
  792. };
  793. GLTFLoader.prototype._loadSkin = function (skin) {
  794. var _this = this;
  795. var skeletonId = "skeleton" + skin.index;
  796. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  797. if (skin.inverseBindMatrices === undefined) {
  798. this._loadBones(skin, null);
  799. }
  800. else {
  801. var accessor = this._gltf.accessors[skin.inverseBindMatrices];
  802. this._loadAccessorAsync(accessor, function (data) {
  803. _this._loadBones(skin, data);
  804. });
  805. }
  806. return skin.babylonSkeleton;
  807. };
  808. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  809. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  810. node.babylonBones = node.babylonBones || {};
  811. node.babylonBones[skin.index] = babylonBone;
  812. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  813. node.babylonAnimationTargets.push(babylonBone);
  814. return babylonBone;
  815. };
  816. GLTFLoader.prototype._loadBones = function (skin, inverseBindMatrixData) {
  817. var babylonBones = {};
  818. for (var i = 0; i < skin.joints.length; i++) {
  819. var node = this._gltf.nodes[skin.joints[i]];
  820. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  821. }
  822. };
  823. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  824. var babylonBone = babylonBones[node.index];
  825. if (babylonBone) {
  826. return babylonBone;
  827. }
  828. var boneIndex = skin.joints.indexOf(node.index);
  829. var baseMatrix = BABYLON.Matrix.Identity();
  830. if (inverseBindMatrixData && boneIndex !== -1) {
  831. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  832. baseMatrix.invertToRef(baseMatrix);
  833. }
  834. var babylonParentBone;
  835. if (node.index != skin.skeleton && node.parent) {
  836. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  837. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  838. }
  839. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  840. babylonBones[node.index] = babylonBone;
  841. return babylonBone;
  842. };
  843. GLTFLoader.prototype._getNodeMatrix = function (node) {
  844. return node.matrix ?
  845. BABYLON.Matrix.FromArray(node.matrix) :
  846. 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());
  847. };
  848. GLTFLoader.prototype._traverseNodes = function (indices, action, parentNode) {
  849. if (parentNode === void 0) { parentNode = null; }
  850. for (var i = 0; i < indices.length; i++) {
  851. this._traverseNode(indices[i], action, parentNode);
  852. }
  853. };
  854. GLTFLoader.prototype._traverseNode = function (index, action, parentNode) {
  855. if (parentNode === void 0) { parentNode = null; }
  856. var node = this._gltf.nodes[index];
  857. if (!action(node, index, parentNode)) {
  858. return;
  859. }
  860. if (node.children) {
  861. for (var i = 0; i < node.children.length; i++) {
  862. this._traverseNode(node.children[i], action, node);
  863. }
  864. }
  865. };
  866. GLTFLoader.prototype._loadAnimations = function () {
  867. var animations = this._gltf.animations;
  868. if (!animations || animations.length === 0) {
  869. return;
  870. }
  871. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  872. var animation = animations[animationIndex];
  873. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  874. this._loadAnimationChannel(animation, animationIndex, channelIndex);
  875. }
  876. }
  877. };
  878. GLTFLoader.prototype._loadAnimationChannel = function (animation, animationIndex, channelIndex) {
  879. var channel = animation.channels[channelIndex];
  880. var samplerIndex = channel.sampler;
  881. var sampler = animation.samplers[samplerIndex];
  882. var targetNode = this._gltf.nodes[channel.target.node];
  883. if (!targetNode) {
  884. BABYLON.Tools.Warn("Animation channel target node (" + channel.target.node + ") does not exist");
  885. return;
  886. }
  887. var targetPath = {
  888. "translation": "position",
  889. "rotation": "rotationQuaternion",
  890. "scale": "scaling",
  891. "weights": "influence"
  892. }[channel.target.path];
  893. if (!targetPath) {
  894. BABYLON.Tools.Warn("Animation channel target path '" + channel.target.path + "' is not valid");
  895. return;
  896. }
  897. var animationType = {
  898. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  899. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  900. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  901. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  902. }[targetPath];
  903. var inputData;
  904. var outputData;
  905. var checkSuccess = function () {
  906. if (!inputData || !outputData) {
  907. return;
  908. }
  909. var outputBufferOffset = 0;
  910. var getNextOutputValue = {
  911. "position": function () {
  912. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  913. outputBufferOffset += 3;
  914. return value;
  915. },
  916. "rotationQuaternion": function () {
  917. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  918. outputBufferOffset += 4;
  919. return value;
  920. },
  921. "scaling": function () {
  922. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  923. outputBufferOffset += 3;
  924. return value;
  925. },
  926. "influence": function () {
  927. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  928. var value = new Array(numTargets);
  929. for (var i = 0; i < numTargets; i++) {
  930. value[i] = outputData[outputBufferOffset++];
  931. }
  932. return value;
  933. },
  934. }[targetPath];
  935. var getNextKey = {
  936. "LINEAR": function (frameIndex) { return ({
  937. frame: inputData[frameIndex],
  938. value: getNextOutputValue()
  939. }); },
  940. "CUBICSPLINE": function (frameIndex) { return ({
  941. frame: inputData[frameIndex],
  942. inTangent: getNextOutputValue(),
  943. value: getNextOutputValue(),
  944. outTangent: getNextOutputValue()
  945. }); },
  946. }[sampler.interpolation];
  947. var keys = new Array(inputData.length);
  948. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  949. keys[frameIndex] = getNextKey(frameIndex);
  950. }
  951. animation.targets = animation.targets || [];
  952. if (targetPath === "influence") {
  953. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  954. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  955. var morphTarget = morphTargetManager.getTarget(targetIndex);
  956. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  957. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  958. babylonAnimation.setKeys(keys.map(function (key) { return ({
  959. frame: key.frame,
  960. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  961. value: key.value[targetIndex],
  962. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  963. }); }));
  964. morphTarget.animations.push(babylonAnimation);
  965. animation.targets.push(morphTarget);
  966. }
  967. }
  968. else {
  969. var animationName = animation.name || "anim" + animationIndex;
  970. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  971. babylonAnimation.setKeys(keys);
  972. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  973. var target = targetNode.babylonAnimationTargets[i];
  974. target.animations.push(babylonAnimation.clone());
  975. animation.targets.push(target);
  976. }
  977. }
  978. };
  979. this._loadAccessorAsync(this._gltf.accessors[sampler.input], function (data) {
  980. inputData = data;
  981. checkSuccess();
  982. });
  983. this._loadAccessorAsync(this._gltf.accessors[sampler.output], function (data) {
  984. outputData = data;
  985. checkSuccess();
  986. });
  987. };
  988. GLTFLoader.prototype._loadBufferAsync = function (index, onSuccess) {
  989. var _this = this;
  990. var buffer = this._gltf.buffers[index];
  991. this.addPendingData(buffer);
  992. if (buffer.loadedData) {
  993. setTimeout(function () {
  994. onSuccess(buffer.loadedData);
  995. _this.removePendingData(buffer);
  996. });
  997. }
  998. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  999. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  1000. buffer.loadedData = new Uint8Array(data);
  1001. setTimeout(function () {
  1002. onSuccess(buffer.loadedData);
  1003. _this.removePendingData(buffer);
  1004. });
  1005. }
  1006. else if (buffer.loadedObservable) {
  1007. buffer.loadedObservable.add(function (buffer) {
  1008. onSuccess(buffer.loadedData);
  1009. _this.removePendingData(buffer);
  1010. });
  1011. }
  1012. else {
  1013. buffer.loadedObservable = new BABYLON.Observable();
  1014. buffer.loadedObservable.add(function (buffer) {
  1015. onSuccess(buffer.loadedData);
  1016. _this.removePendingData(buffer);
  1017. });
  1018. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  1019. buffer.loadedData = new Uint8Array(data);
  1020. buffer.loadedObservable.notifyObservers(buffer);
  1021. buffer.loadedObservable = null;
  1022. }, function (event) {
  1023. if (!_this._disposed) {
  1024. _this._onProgress(event);
  1025. }
  1026. }, this._babylonScene.database, true, function (request) {
  1027. if (!_this._disposed) {
  1028. _this._onError("Failed to load file '" + buffer.uri + "': " + request.status + " " + request.statusText);
  1029. _this.removePendingData(buffer);
  1030. }
  1031. });
  1032. }
  1033. };
  1034. GLTFLoader.prototype._buildInt8ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  1035. if (!byteStride) {
  1036. return new Int8Array(buffer, byteOffset, byteLength);
  1037. }
  1038. var sourceBuffer = new Int8Array(buffer, byteOffset);
  1039. var targetBuffer = new Int8Array(byteLength);
  1040. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride, targetBuffer.length);
  1041. return targetBuffer;
  1042. };
  1043. GLTFLoader.prototype._buildUint8ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  1044. if (!byteStride) {
  1045. return new Uint8Array(buffer, byteOffset, byteLength);
  1046. }
  1047. var sourceBuffer = new Uint8Array(buffer, byteOffset);
  1048. var targetBuffer = new Uint8Array(byteLength);
  1049. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride, targetBuffer.length);
  1050. return targetBuffer;
  1051. };
  1052. GLTFLoader.prototype._buildInt16ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  1053. if (!byteStride) {
  1054. return new Int16Array(buffer, byteOffset, byteLength);
  1055. }
  1056. var sourceBuffer = new Int16Array(buffer, byteOffset);
  1057. var targetBuffer = new Int16Array(byteLength);
  1058. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 2, targetBuffer.length);
  1059. return targetBuffer;
  1060. };
  1061. GLTFLoader.prototype._buildUint16ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  1062. if (!byteStride) {
  1063. return new Uint16Array(buffer, byteOffset, byteLength);
  1064. }
  1065. var sourceBuffer = new Uint16Array(buffer, byteOffset);
  1066. var targetBuffer = new Uint16Array(byteLength);
  1067. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 2, targetBuffer.length);
  1068. return targetBuffer;
  1069. };
  1070. GLTFLoader.prototype._buildUint32ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  1071. if (!byteStride) {
  1072. return new Uint32Array(buffer, byteOffset, byteLength);
  1073. }
  1074. var sourceBuffer = new Uint32Array(buffer, byteOffset);
  1075. var targetBuffer = new Uint32Array(byteLength);
  1076. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 4, targetBuffer.length);
  1077. return targetBuffer;
  1078. };
  1079. GLTFLoader.prototype._buildFloat32ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  1080. if (!byteStride) {
  1081. return new Float32Array(buffer, byteOffset, byteLength);
  1082. }
  1083. var sourceBuffer = new Float32Array(buffer, byteOffset);
  1084. var targetBuffer = new Float32Array(byteLength);
  1085. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 4, targetBuffer.length);
  1086. return targetBuffer;
  1087. };
  1088. GLTFLoader.prototype._extractInterleavedData = function (sourceBuffer, targetBuffer, bytePerComponent, stride, length) {
  1089. var tempIndex = 0;
  1090. var sourceIndex = 0;
  1091. var storageSize = bytePerComponent;
  1092. while (tempIndex < length) {
  1093. for (var cursor = 0; cursor < storageSize; cursor++) {
  1094. targetBuffer[tempIndex] = sourceBuffer[sourceIndex + cursor];
  1095. tempIndex++;
  1096. }
  1097. sourceIndex += stride;
  1098. }
  1099. };
  1100. GLTFLoader.prototype._loadBufferViewAsync = function (bufferView, byteOffset, byteLength, bytePerComponent, componentType, onSuccess) {
  1101. var _this = this;
  1102. byteOffset += (bufferView.byteOffset || 0);
  1103. this._loadBufferAsync(bufferView.buffer, function (bufferData) {
  1104. if (byteOffset + byteLength > bufferData.byteLength) {
  1105. _this._onError("Buffer access is out of range");
  1106. return;
  1107. }
  1108. var buffer = bufferData.buffer;
  1109. byteOffset += bufferData.byteOffset;
  1110. var bufferViewData;
  1111. switch (componentType) {
  1112. case GLTF2.EComponentType.BYTE:
  1113. bufferViewData = _this._buildInt8ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  1114. break;
  1115. case GLTF2.EComponentType.UNSIGNED_BYTE:
  1116. bufferViewData = _this._buildUint8ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  1117. break;
  1118. case GLTF2.EComponentType.SHORT:
  1119. bufferViewData = _this._buildInt16ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  1120. break;
  1121. case GLTF2.EComponentType.UNSIGNED_SHORT:
  1122. bufferViewData = _this._buildUint16ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  1123. break;
  1124. case GLTF2.EComponentType.UNSIGNED_INT:
  1125. bufferViewData = _this._buildUint32ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  1126. break;
  1127. case GLTF2.EComponentType.FLOAT:
  1128. bufferViewData = _this._buildFloat32ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  1129. break;
  1130. default:
  1131. _this._onError("Invalid component type (" + componentType + ")");
  1132. return;
  1133. }
  1134. onSuccess(bufferViewData);
  1135. });
  1136. };
  1137. GLTFLoader.prototype._loadAccessorAsync = function (accessor, onSuccess) {
  1138. var bufferView = this._gltf.bufferViews[accessor.bufferView];
  1139. var byteOffset = accessor.byteOffset || 0;
  1140. var bytePerComponent = this._getByteStrideFromType(accessor);
  1141. var byteLength = accessor.count * bytePerComponent;
  1142. this._loadBufferViewAsync(bufferView, byteOffset, byteLength, bytePerComponent, accessor.componentType, onSuccess);
  1143. };
  1144. GLTFLoader.prototype._getByteStrideFromType = function (accessor) {
  1145. switch (accessor.type) {
  1146. case "SCALAR": return 1;
  1147. case "VEC2": return 2;
  1148. case "VEC3": return 3;
  1149. case "VEC4": return 4;
  1150. case "MAT2": return 4;
  1151. case "MAT3": return 9;
  1152. case "MAT4": return 16;
  1153. default:
  1154. this._onError("Invalid accessor type (" + accessor.type + ")");
  1155. return 0;
  1156. }
  1157. };
  1158. Object.defineProperty(GLTFLoader.prototype, "blockPendingTracking", {
  1159. set: function (value) {
  1160. this._blockPendingTracking = value;
  1161. },
  1162. enumerable: true,
  1163. configurable: true
  1164. });
  1165. GLTFLoader.prototype.addPendingData = function (data) {
  1166. if (!this._renderReady) {
  1167. this._renderPendingCount++;
  1168. }
  1169. this.addLoaderPendingData(data);
  1170. };
  1171. GLTFLoader.prototype.removePendingData = function (data) {
  1172. if (!this._renderReady) {
  1173. if (--this._renderPendingCount === 0) {
  1174. this._renderReady = true;
  1175. this._onRenderReady();
  1176. }
  1177. }
  1178. this.removeLoaderPendingData(data);
  1179. };
  1180. GLTFLoader.prototype.addLoaderNonBlockingPendingData = function (data) {
  1181. if (!this._nonBlockingData) {
  1182. this._nonBlockingData = new Array();
  1183. }
  1184. this._nonBlockingData.push(data);
  1185. };
  1186. GLTFLoader.prototype.addLoaderPendingData = function (data) {
  1187. if (this._blockPendingTracking) {
  1188. this.addLoaderNonBlockingPendingData(data);
  1189. return;
  1190. }
  1191. this._loaderPendingCount++;
  1192. };
  1193. GLTFLoader.prototype.removeLoaderPendingData = function (data) {
  1194. var indexInPending = this._nonBlockingData ? this._nonBlockingData.indexOf(data) : -1;
  1195. if (indexInPending !== -1) {
  1196. this._nonBlockingData.splice(indexInPending, 1);
  1197. }
  1198. else if (--this._loaderPendingCount === 0) {
  1199. this._onLoaderFirstLODComplete();
  1200. }
  1201. if ((!this._nonBlockingData || this._nonBlockingData.length === 0) && this._loaderPendingCount === 0) {
  1202. this._onLoaderComplete();
  1203. this.dispose();
  1204. }
  1205. };
  1206. GLTFLoader.prototype._getDefaultMaterial = function () {
  1207. if (!this._defaultMaterial) {
  1208. var id = "__gltf_default";
  1209. var material = this._babylonScene.getMaterialByName(id);
  1210. if (!material) {
  1211. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  1212. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1213. material.metallic = 1;
  1214. material.roughness = 1;
  1215. }
  1216. this._defaultMaterial = material;
  1217. }
  1218. return this._defaultMaterial;
  1219. };
  1220. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (material) {
  1221. var babylonMaterial = material.babylonMaterial;
  1222. // Ensure metallic workflow
  1223. babylonMaterial.metallic = 1;
  1224. babylonMaterial.roughness = 1;
  1225. var properties = material.pbrMetallicRoughness;
  1226. if (!properties) {
  1227. return;
  1228. }
  1229. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  1230. babylonMaterial.metallic = properties.metallicFactor === undefined ? 1 : properties.metallicFactor;
  1231. babylonMaterial.roughness = properties.roughnessFactor === undefined ? 1 : properties.roughnessFactor;
  1232. if (properties.baseColorTexture) {
  1233. babylonMaterial.albedoTexture = this.loadTexture(properties.baseColorTexture);
  1234. }
  1235. if (properties.metallicRoughnessTexture) {
  1236. babylonMaterial.metallicTexture = this.loadTexture(properties.metallicRoughnessTexture);
  1237. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1238. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1239. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1240. }
  1241. this.loadMaterialAlphaProperties(material, properties.baseColorFactor);
  1242. };
  1243. GLTFLoader.prototype.loadMaterial = function (material, assign) {
  1244. if (material.babylonMaterial) {
  1245. assign(material.babylonMaterial, false);
  1246. return;
  1247. }
  1248. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, material, assign)) {
  1249. return;
  1250. }
  1251. this.createPbrMaterial(material);
  1252. this.loadMaterialBaseProperties(material);
  1253. this._loadMaterialMetallicRoughnessProperties(material);
  1254. assign(material.babylonMaterial, true);
  1255. };
  1256. GLTFLoader.prototype.createPbrMaterial = function (material) {
  1257. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  1258. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1259. material.babylonMaterial = babylonMaterial;
  1260. };
  1261. GLTFLoader.prototype.loadMaterialBaseProperties = function (material) {
  1262. var babylonMaterial = material.babylonMaterial;
  1263. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  1264. if (material.doubleSided) {
  1265. babylonMaterial.backFaceCulling = false;
  1266. babylonMaterial.twoSidedLighting = true;
  1267. }
  1268. if (material.normalTexture) {
  1269. babylonMaterial.bumpTexture = this.loadTexture(material.normalTexture);
  1270. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  1271. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  1272. if (material.normalTexture.scale !== undefined) {
  1273. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1274. }
  1275. }
  1276. if (material.occlusionTexture) {
  1277. babylonMaterial.ambientTexture = this.loadTexture(material.occlusionTexture);
  1278. babylonMaterial.useAmbientInGrayScale = true;
  1279. if (material.occlusionTexture.strength !== undefined) {
  1280. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1281. }
  1282. }
  1283. if (material.emissiveTexture) {
  1284. babylonMaterial.emissiveTexture = this.loadTexture(material.emissiveTexture);
  1285. }
  1286. };
  1287. GLTFLoader.prototype.loadMaterialAlphaProperties = function (material, colorFactor) {
  1288. var babylonMaterial = material.babylonMaterial;
  1289. var alphaMode = material.alphaMode || "OPAQUE";
  1290. switch (alphaMode) {
  1291. case "OPAQUE":
  1292. // default is opaque
  1293. break;
  1294. case "MASK":
  1295. case "BLEND":
  1296. if (colorFactor) {
  1297. babylonMaterial.alpha = colorFactor[3];
  1298. }
  1299. if (babylonMaterial.albedoTexture) {
  1300. babylonMaterial.albedoTexture.hasAlpha = true;
  1301. babylonMaterial.useAlphaFromAlbedoTexture = (alphaMode === "BLEND");
  1302. }
  1303. break;
  1304. default:
  1305. BABYLON.Tools.Warn("Invalid alpha mode '" + material.alphaMode + "'");
  1306. break;
  1307. }
  1308. babylonMaterial.alphaCutOff = material.alphaCutoff === undefined ? 0.5 : material.alphaCutoff;
  1309. };
  1310. GLTFLoader.prototype.loadTexture = function (textureInfo) {
  1311. var _this = this;
  1312. var texture = this._gltf.textures[textureInfo.index];
  1313. var texCoord = textureInfo.texCoord || 0;
  1314. if (!texture || texture.source === undefined) {
  1315. return null;
  1316. }
  1317. var source = this._gltf.images[texture.source];
  1318. var sampler = (texture.sampler === undefined ? {} : this._gltf.samplers[texture.sampler]);
  1319. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  1320. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  1321. this.addPendingData(texture);
  1322. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  1323. if (!_this._disposed) {
  1324. _this.removePendingData(texture);
  1325. }
  1326. }, function () {
  1327. if (!_this._disposed) {
  1328. _this._onError("Failed to load texture '" + source.uri + "'");
  1329. _this.removePendingData(texture);
  1330. }
  1331. });
  1332. if (texture.url) {
  1333. babylonTexture.updateURL(texture.url);
  1334. }
  1335. else if (texture.dataReadyObservable) {
  1336. texture.dataReadyObservable.add(function (texture) {
  1337. babylonTexture.updateURL(texture.url);
  1338. });
  1339. }
  1340. else {
  1341. texture.dataReadyObservable = new BABYLON.Observable();
  1342. texture.dataReadyObservable.add(function (texture) {
  1343. babylonTexture.updateURL(texture.url);
  1344. });
  1345. var setTextureData = function (data) {
  1346. texture.url = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  1347. texture.dataReadyObservable.notifyObservers(texture);
  1348. };
  1349. if (!source.uri) {
  1350. var bufferView = this._gltf.bufferViews[source.bufferView];
  1351. this._loadBufferViewAsync(bufferView, 0, bufferView.byteLength, 1, GLTF2.EComponentType.UNSIGNED_BYTE, setTextureData);
  1352. }
  1353. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  1354. setTextureData(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri)));
  1355. }
  1356. else {
  1357. BABYLON.Tools.LoadFile(this._rootUrl + source.uri, setTextureData, function (event) {
  1358. if (!_this._disposed) {
  1359. _this._onProgress(event);
  1360. }
  1361. }, this._babylonScene.database, true, function (request) {
  1362. _this._onError("Failed to load file '" + source.uri + "': " + request.status + " " + request.statusText);
  1363. });
  1364. }
  1365. }
  1366. babylonTexture.coordinatesIndex = texCoord;
  1367. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  1368. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  1369. babylonTexture.name = texture.name || "texture" + textureInfo.index;
  1370. if (this._parent.onTextureLoaded) {
  1371. this._parent.onTextureLoaded(babylonTexture);
  1372. }
  1373. return babylonTexture;
  1374. };
  1375. GLTFLoader.Extensions = {};
  1376. return GLTFLoader;
  1377. }());
  1378. GLTF2.GLTFLoader = GLTFLoader;
  1379. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  1380. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1381. })(BABYLON || (BABYLON = {}));
  1382. //# sourceMappingURL=babylon.glTFLoader.js.map
  1383. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1384. var BABYLON;
  1385. (function (BABYLON) {
  1386. var GLTF2;
  1387. (function (GLTF2) {
  1388. /**
  1389. * Utils functions for GLTF
  1390. */
  1391. var GLTFUtils = (function () {
  1392. function GLTFUtils() {
  1393. }
  1394. /**
  1395. * If the uri is a base64 string
  1396. * @param uri: the uri to test
  1397. */
  1398. GLTFUtils.IsBase64 = function (uri) {
  1399. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1400. };
  1401. /**
  1402. * Decode the base64 uri
  1403. * @param uri: the uri to decode
  1404. */
  1405. GLTFUtils.DecodeBase64 = function (uri) {
  1406. var decodedString = atob(uri.split(",")[1]);
  1407. var bufferLength = decodedString.length;
  1408. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1409. for (var i = 0; i < bufferLength; i++) {
  1410. bufferView[i] = decodedString.charCodeAt(i);
  1411. }
  1412. return bufferView.buffer;
  1413. };
  1414. GLTFUtils.ForEach = function (view, func) {
  1415. for (var index = 0; index < view.length; index++) {
  1416. func(view[index], index);
  1417. }
  1418. };
  1419. GLTFUtils.GetTextureWrapMode = function (mode) {
  1420. // Set defaults if undefined
  1421. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  1422. switch (mode) {
  1423. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1424. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1425. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1426. default:
  1427. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  1428. return BABYLON.Texture.WRAP_ADDRESSMODE;
  1429. }
  1430. };
  1431. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  1432. // Set defaults if undefined
  1433. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  1434. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  1435. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  1436. switch (minFilter) {
  1437. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  1438. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  1439. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  1440. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  1441. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  1442. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  1443. default:
  1444. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  1445. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  1446. }
  1447. }
  1448. else {
  1449. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  1450. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  1451. }
  1452. switch (minFilter) {
  1453. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  1454. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  1455. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  1456. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  1457. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  1458. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  1459. default:
  1460. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  1461. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  1462. }
  1463. }
  1464. };
  1465. /**
  1466. * Decodes a buffer view into a string
  1467. * @param view: the buffer view
  1468. */
  1469. GLTFUtils.DecodeBufferToText = function (view) {
  1470. var result = "";
  1471. var length = view.byteLength;
  1472. for (var i = 0; i < length; ++i) {
  1473. result += String.fromCharCode(view[i]);
  1474. }
  1475. return result;
  1476. };
  1477. return GLTFUtils;
  1478. }());
  1479. GLTF2.GLTFUtils = GLTFUtils;
  1480. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1481. })(BABYLON || (BABYLON = {}));
  1482. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  1483. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1484. var BABYLON;
  1485. (function (BABYLON) {
  1486. var GLTF2;
  1487. (function (GLTF2) {
  1488. var GLTFLoaderExtension = (function () {
  1489. function GLTFLoaderExtension() {
  1490. this.enabled = true;
  1491. }
  1492. GLTFLoaderExtension.prototype.loadMaterial = function (loader, material, assign) { return false; };
  1493. GLTFLoaderExtension.LoadMaterial = function (loader, material, assign) {
  1494. return this._ApplyExtensions(function (extension) { return extension.loadMaterial(loader, material, assign); });
  1495. };
  1496. GLTFLoaderExtension._ApplyExtensions = function (action) {
  1497. var extensions = GLTFLoaderExtension._Extensions;
  1498. if (!extensions) {
  1499. return;
  1500. }
  1501. for (var i = 0; i < extensions.length; i++) {
  1502. var extension = extensions[i];
  1503. if (extension.enabled && action(extension)) {
  1504. return true;
  1505. }
  1506. }
  1507. return false;
  1508. };
  1509. //
  1510. // Utilities
  1511. //
  1512. GLTFLoaderExtension._Extensions = [];
  1513. return GLTFLoaderExtension;
  1514. }());
  1515. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  1516. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1517. })(BABYLON || (BABYLON = {}));
  1518. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  1519. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  1520. var __extends = (this && this.__extends) || (function () {
  1521. var extendStatics = Object.setPrototypeOf ||
  1522. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1523. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1524. return function (d, b) {
  1525. extendStatics(d, b);
  1526. function __() { this.constructor = d; }
  1527. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1528. };
  1529. })();
  1530. var BABYLON;
  1531. (function (BABYLON) {
  1532. var GLTF2;
  1533. (function (GLTF2) {
  1534. var Extensions;
  1535. (function (Extensions) {
  1536. var MSFTLOD = (function (_super) {
  1537. __extends(MSFTLOD, _super);
  1538. function MSFTLOD() {
  1539. return _super !== null && _super.apply(this, arguments) || this;
  1540. }
  1541. Object.defineProperty(MSFTLOD.prototype, "name", {
  1542. get: function () {
  1543. return "MSFT_lod";
  1544. },
  1545. enumerable: true,
  1546. configurable: true
  1547. });
  1548. MSFTLOD.prototype.loadMaterial = function (loader, material, assign) {
  1549. if (!material.extensions) {
  1550. return false;
  1551. }
  1552. var properties = material.extensions[this.name];
  1553. if (!properties) {
  1554. return false;
  1555. }
  1556. // Clear out the extension so that it won't get loaded again.
  1557. material.extensions[this.name] = undefined;
  1558. // Tell the loader not to clear its state until the highest LOD is loaded.
  1559. var materialLODs = [material.index].concat(properties.ids);
  1560. loader.addLoaderPendingData(material);
  1561. for (var index = 0; index < materialLODs.length; index++) {
  1562. loader.addLoaderNonBlockingPendingData(index);
  1563. }
  1564. // Start with the lowest quality LOD.
  1565. this.loadMaterialLOD(loader, material, materialLODs, materialLODs.length - 1, assign);
  1566. return true;
  1567. };
  1568. MSFTLOD.prototype.loadMaterialLOD = function (loader, material, materialLODs, lod, assign) {
  1569. var _this = this;
  1570. var materialLOD = loader.gltf.materials[materialLODs[lod]];
  1571. if (lod !== materialLODs.length - 1) {
  1572. loader.blockPendingTracking = true;
  1573. }
  1574. loader.loadMaterial(materialLOD, function (babylonMaterial, isNew) {
  1575. assign(babylonMaterial, isNew);
  1576. loader.removeLoaderPendingData(lod);
  1577. // Loading is considered complete if this is the lowest quality LOD.
  1578. if (lod === materialLODs.length - 1) {
  1579. loader.removeLoaderPendingData(material);
  1580. }
  1581. if (lod === 0) {
  1582. loader.blockPendingTracking = false;
  1583. return;
  1584. }
  1585. // Load the next LOD when the loader is ready to render and
  1586. // all active material textures of the current LOD are loaded.
  1587. loader.executeWhenRenderReady(function () {
  1588. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  1589. setTimeout(function () {
  1590. _this.loadMaterialLOD(loader, material, materialLODs, lod - 1, assign);
  1591. }, MSFTLOD.MinimalLODDelay);
  1592. });
  1593. });
  1594. });
  1595. };
  1596. /**
  1597. * Specify the minimal delay between LODs in ms (default = 250)
  1598. */
  1599. MSFTLOD.MinimalLODDelay = 250;
  1600. return MSFTLOD;
  1601. }(GLTF2.GLTFLoaderExtension));
  1602. Extensions.MSFTLOD = MSFTLOD;
  1603. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  1604. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  1605. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1606. })(BABYLON || (BABYLON = {}));
  1607. //# sourceMappingURL=MSFT_lod.js.map
  1608. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  1609. var __extends = (this && this.__extends) || (function () {
  1610. var extendStatics = Object.setPrototypeOf ||
  1611. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1612. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1613. return function (d, b) {
  1614. extendStatics(d, b);
  1615. function __() { this.constructor = d; }
  1616. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1617. };
  1618. })();
  1619. var BABYLON;
  1620. (function (BABYLON) {
  1621. var GLTF2;
  1622. (function (GLTF2) {
  1623. var Extensions;
  1624. (function (Extensions) {
  1625. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  1626. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  1627. function KHRMaterialsPbrSpecularGlossiness() {
  1628. return _super !== null && _super.apply(this, arguments) || this;
  1629. }
  1630. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  1631. get: function () {
  1632. return "KHR_materials_pbrSpecularGlossiness";
  1633. },
  1634. enumerable: true,
  1635. configurable: true
  1636. });
  1637. KHRMaterialsPbrSpecularGlossiness.prototype.loadMaterial = function (loader, material, assign) {
  1638. if (!material.extensions) {
  1639. return false;
  1640. }
  1641. var properties = material.extensions[this.name];
  1642. if (!properties) {
  1643. return false;
  1644. }
  1645. loader.createPbrMaterial(material);
  1646. loader.loadMaterialBaseProperties(material);
  1647. this._loadSpecularGlossinessProperties(loader, material, properties);
  1648. assign(material.babylonMaterial, true);
  1649. return true;
  1650. };
  1651. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, material, properties) {
  1652. var babylonMaterial = material.babylonMaterial;
  1653. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  1654. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  1655. babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  1656. if (properties.diffuseTexture) {
  1657. babylonMaterial.albedoTexture = loader.loadTexture(properties.diffuseTexture);
  1658. }
  1659. if (properties.specularGlossinessTexture) {
  1660. babylonMaterial.reflectivityTexture = loader.loadTexture(properties.specularGlossinessTexture);
  1661. babylonMaterial.reflectivityTexture.hasAlpha = true;
  1662. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  1663. }
  1664. loader.loadMaterialAlphaProperties(material, properties.diffuseFactor);
  1665. };
  1666. return KHRMaterialsPbrSpecularGlossiness;
  1667. }(GLTF2.GLTFLoaderExtension));
  1668. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  1669. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  1670. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  1671. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1672. })(BABYLON || (BABYLON = {}));
  1673. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map