babylon.glTF2FileLoader.js 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. var GLTFFileLoader = (function () {
  5. function GLTFFileLoader() {
  6. this.extensions = {
  7. ".gltf": { isBinary: false },
  8. ".glb": { isBinary: true }
  9. };
  10. }
  11. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onError) {
  12. var loaderData = GLTFFileLoader._parse(data);
  13. var loader = this._getLoader(loaderData);
  14. if (!loader) {
  15. onError();
  16. return;
  17. }
  18. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onError);
  19. };
  20. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  21. var loaderData = GLTFFileLoader._parse(data);
  22. var loader = this._getLoader(loaderData);
  23. if (!loader) {
  24. onError();
  25. return;
  26. }
  27. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onError);
  28. };
  29. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  30. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  31. };
  32. GLTFFileLoader._parse = function (data) {
  33. if (data instanceof ArrayBuffer) {
  34. return GLTFFileLoader._parseBinary(data);
  35. }
  36. return {
  37. json: JSON.parse(data),
  38. bin: null
  39. };
  40. };
  41. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  42. var loaderVersion = { major: 2, minor: 0 };
  43. var asset = loaderData.json.asset || {};
  44. var version = GLTFFileLoader._parseVersion(asset.version);
  45. if (!version) {
  46. BABYLON.Tools.Error("Invalid version");
  47. return null;
  48. }
  49. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  50. if (minVersion) {
  51. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  52. BABYLON.Tools.Error("Incompatible version");
  53. return null;
  54. }
  55. }
  56. var loaders = {
  57. 1: GLTFFileLoader.GLTFLoaderV1,
  58. 2: GLTFFileLoader.GLTFLoaderV2
  59. };
  60. var loader = loaders[version.major];
  61. if (loader === undefined) {
  62. BABYLON.Tools.Error("Unsupported version");
  63. return null;
  64. }
  65. if (loader === null) {
  66. BABYLON.Tools.Error("v" + version.major + " loader is not available");
  67. return null;
  68. }
  69. return loader;
  70. };
  71. GLTFFileLoader._parseBinary = function (data) {
  72. var Binary = {
  73. Magic: 0x46546C67
  74. };
  75. var binaryReader = new BinaryReader(data);
  76. var magic = binaryReader.readUint32();
  77. if (magic !== Binary.Magic) {
  78. BABYLON.Tools.Error("Unexpected magic: " + magic);
  79. return null;
  80. }
  81. var version = binaryReader.readUint32();
  82. switch (version) {
  83. case 1: return GLTFFileLoader._parseV1(binaryReader);
  84. case 2: return GLTFFileLoader._parseV2(binaryReader);
  85. }
  86. BABYLON.Tools.Error("Unsupported version: " + version);
  87. return null;
  88. };
  89. GLTFFileLoader._parseV1 = function (binaryReader) {
  90. var ContentFormat = {
  91. JSON: 0
  92. };
  93. var length = binaryReader.readUint32();
  94. if (length != binaryReader.getLength()) {
  95. BABYLON.Tools.Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  96. return null;
  97. }
  98. var contentLength = binaryReader.readUint32();
  99. var contentFormat = binaryReader.readUint32();
  100. var content;
  101. switch (contentFormat) {
  102. case ContentFormat.JSON:
  103. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  104. break;
  105. default:
  106. BABYLON.Tools.Error("Unexpected content format: " + contentFormat);
  107. return null;
  108. }
  109. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  110. var body = binaryReader.readUint8Array(bytesRemaining);
  111. return {
  112. json: content,
  113. bin: body
  114. };
  115. };
  116. GLTFFileLoader._parseV2 = function (binaryReader) {
  117. var ChunkFormat = {
  118. JSON: 0x4E4F534A,
  119. BIN: 0x004E4942
  120. };
  121. var length = binaryReader.readUint32();
  122. if (length !== binaryReader.getLength()) {
  123. BABYLON.Tools.Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  124. return null;
  125. }
  126. // JSON chunk
  127. var chunkLength = binaryReader.readUint32();
  128. var chunkFormat = binaryReader.readUint32();
  129. if (chunkFormat !== ChunkFormat.JSON) {
  130. BABYLON.Tools.Error("First chunk format is not JSON");
  131. return null;
  132. }
  133. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  134. // Look for BIN chunk
  135. var bin = null;
  136. while (binaryReader.getPosition() < binaryReader.getLength()) {
  137. chunkLength = binaryReader.readUint32();
  138. chunkFormat = binaryReader.readUint32();
  139. switch (chunkFormat) {
  140. case ChunkFormat.JSON:
  141. BABYLON.Tools.Error("Unexpected JSON chunk");
  142. return null;
  143. case ChunkFormat.BIN:
  144. bin = binaryReader.readUint8Array(chunkLength);
  145. break;
  146. default:
  147. // ignore unrecognized chunkFormat
  148. binaryReader.skipBytes(chunkLength);
  149. break;
  150. }
  151. }
  152. return {
  153. json: json,
  154. bin: bin
  155. };
  156. };
  157. GLTFFileLoader._parseVersion = function (version) {
  158. if (!version) {
  159. return null;
  160. }
  161. var parts = version.split(".");
  162. if (parts.length === 0) {
  163. return null;
  164. }
  165. var major = parseInt(parts[0]);
  166. if (major > 1 && parts.length != 2) {
  167. return null;
  168. }
  169. var minor = parseInt(parts[1]);
  170. return {
  171. major: major,
  172. minor: parseInt(parts[0])
  173. };
  174. };
  175. GLTFFileLoader._compareVersion = function (a, b) {
  176. if (a.major > b.major)
  177. return 1;
  178. if (a.major < b.major)
  179. return -1;
  180. if (a.minor > b.minor)
  181. return 1;
  182. if (a.minor < b.minor)
  183. return -1;
  184. return 0;
  185. };
  186. GLTFFileLoader._decodeBufferToText = function (view) {
  187. var result = "";
  188. var length = view.byteLength;
  189. for (var i = 0; i < length; ++i) {
  190. result += String.fromCharCode(view[i]);
  191. }
  192. return result;
  193. };
  194. return GLTFFileLoader;
  195. }());
  196. GLTFFileLoader.GLTFLoaderV1 = null;
  197. GLTFFileLoader.GLTFLoaderV2 = null;
  198. GLTFFileLoader.HomogeneousCoordinates = false;
  199. GLTFFileLoader.IncrementalLoading = true;
  200. BABYLON.GLTFFileLoader = GLTFFileLoader;
  201. var BinaryReader = (function () {
  202. function BinaryReader(arrayBuffer) {
  203. this._arrayBuffer = arrayBuffer;
  204. this._dataView = new DataView(arrayBuffer);
  205. this._byteOffset = 0;
  206. }
  207. BinaryReader.prototype.getPosition = function () {
  208. return this._byteOffset;
  209. };
  210. BinaryReader.prototype.getLength = function () {
  211. return this._arrayBuffer.byteLength;
  212. };
  213. BinaryReader.prototype.readUint32 = function () {
  214. var value = this._dataView.getUint32(this._byteOffset, true);
  215. this._byteOffset += 4;
  216. return value;
  217. };
  218. BinaryReader.prototype.readUint8Array = function (length) {
  219. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  220. this._byteOffset += length;
  221. return value;
  222. };
  223. BinaryReader.prototype.skipBytes = function (length) {
  224. this._byteOffset += length;
  225. };
  226. return BinaryReader;
  227. }());
  228. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  229. })(BABYLON || (BABYLON = {}));
  230. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  231. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  232. var BABYLON;
  233. (function (BABYLON) {
  234. var GLTF2;
  235. (function (GLTF2) {
  236. /**
  237. * Enums
  238. */
  239. var EComponentType;
  240. (function (EComponentType) {
  241. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  242. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  243. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  244. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  245. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  246. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  247. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  248. var EMeshPrimitiveMode;
  249. (function (EMeshPrimitiveMode) {
  250. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  251. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  252. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  253. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  254. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  255. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  256. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  257. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  258. var ETextureMagFilter;
  259. (function (ETextureMagFilter) {
  260. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  261. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  262. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  263. var ETextureMinFilter;
  264. (function (ETextureMinFilter) {
  265. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  266. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  267. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  268. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  269. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  270. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  271. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  272. var ETextureWrapMode;
  273. (function (ETextureWrapMode) {
  274. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  275. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  276. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  277. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  278. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  279. })(BABYLON || (BABYLON = {}));
  280. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  281. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  282. var BABYLON;
  283. (function (BABYLON) {
  284. var GLTF2;
  285. (function (GLTF2) {
  286. var GLTFLoader = (function () {
  287. function GLTFLoader() {
  288. }
  289. GLTFLoader.RegisterExtension = function (extension) {
  290. if (GLTFLoader.Extensions[extension.name]) {
  291. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  292. return;
  293. }
  294. GLTFLoader.Extensions[extension.name] = extension;
  295. // Keep the order of registration so that extensions registered first are called first.
  296. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  297. };
  298. Object.defineProperty(GLTFLoader.prototype, "gltf", {
  299. get: function () {
  300. return this._gltf;
  301. },
  302. enumerable: true,
  303. configurable: true
  304. });
  305. Object.defineProperty(GLTFLoader.prototype, "babylonScene", {
  306. get: function () {
  307. return this._babylonScene;
  308. },
  309. enumerable: true,
  310. configurable: true
  311. });
  312. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onError) {
  313. var _this = this;
  314. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  315. var meshes = [];
  316. if (_this._gltf.nodes) {
  317. for (var i = 0; i < _this._gltf.nodes.length; i++) {
  318. var node = _this._gltf.nodes[i];
  319. if (node.babylonMesh) {
  320. meshes.push(node.babylonMesh);
  321. }
  322. }
  323. }
  324. var skeletons = [];
  325. if (_this._gltf.skins) {
  326. for (var i = 0; i < _this._gltf.skins.length; i++) {
  327. var skin = _this._gltf.skins[i];
  328. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  329. skeletons.push(skin.babylonSkeleton);
  330. }
  331. }
  332. }
  333. onSuccess(meshes, null, skeletons);
  334. }, onError);
  335. };
  336. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  337. this._loadAsync(null, scene, data, rootUrl, onSuccess, onError);
  338. };
  339. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onError) {
  340. scene.useRightHandedSystem = true;
  341. this._clear();
  342. this._loadData(data);
  343. this._babylonScene = scene;
  344. this._rootUrl = rootUrl;
  345. this._onSuccess = onSuccess;
  346. this._onError = onError;
  347. this.addPendingData(this);
  348. this._loadScene(nodeNames);
  349. this._loadAnimations();
  350. this.removePendingData(this);
  351. };
  352. GLTFLoader.prototype._onRenderReady = function () {
  353. this._showMeshes();
  354. this._startAnimations();
  355. if (this._errors.length === 0) {
  356. this._onSuccess();
  357. }
  358. else {
  359. this._errors.forEach(function (error) { return BABYLON.Tools.Error(error); });
  360. this._errors = [];
  361. this._onError();
  362. }
  363. };
  364. GLTFLoader.prototype._onLoaderComplete = function () {
  365. this._errors.forEach(function (error) { return BABYLON.Tools.Error(error); });
  366. this._errors = [];
  367. this._clear();
  368. };
  369. GLTFLoader.prototype._loadData = function (data) {
  370. this._gltf = data.json;
  371. var binaryBuffer;
  372. var buffers = this._gltf.buffers;
  373. if (buffers.length > 0 && buffers[0].uri === undefined) {
  374. binaryBuffer = buffers[0];
  375. }
  376. if (data.bin) {
  377. if (binaryBuffer) {
  378. if (binaryBuffer.byteLength != data.bin.byteLength) {
  379. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  380. }
  381. }
  382. else {
  383. BABYLON.Tools.Warn("Unexpected BIN chunk");
  384. }
  385. binaryBuffer.loadedData = data.bin;
  386. }
  387. };
  388. GLTFLoader.prototype._showMeshes = function () {
  389. var nodes = this._gltf.nodes;
  390. for (var i = 0; i < nodes.length; i++) {
  391. var node = nodes[i];
  392. if (node.babylonMesh) {
  393. node.babylonMesh.isVisible = true;
  394. }
  395. }
  396. };
  397. GLTFLoader.prototype._startAnimations = function () {
  398. var animations = this._gltf.animations;
  399. if (!animations) {
  400. return;
  401. }
  402. for (var i = 0; i < animations.length; i++) {
  403. var animation = animations[i];
  404. for (var j = 0; j < animation.targets.length; j++) {
  405. this._babylonScene.beginAnimation(animation.targets[j], 0, Number.MAX_VALUE, true);
  406. }
  407. }
  408. };
  409. GLTFLoader.prototype._clear = function () {
  410. // Revoke object urls created during load
  411. if (this._gltf && this._gltf.textures) {
  412. for (var i = 0; i < this._gltf.textures.length; i++) {
  413. var texture = this._gltf.textures[i];
  414. if (texture.blobURL) {
  415. URL.revokeObjectURL(texture.blobURL);
  416. }
  417. }
  418. }
  419. this._gltf = undefined;
  420. this._errors = [];
  421. this._babylonScene = undefined;
  422. this._rootUrl = undefined;
  423. this._defaultMaterial = undefined;
  424. this._onSuccess = undefined;
  425. this._onError = undefined;
  426. this._renderReady = false;
  427. this._renderPendingCount = 0;
  428. this._loaderPendingCount = 0;
  429. };
  430. GLTFLoader.prototype._loadScene = function (nodeNames) {
  431. var _this = this;
  432. var scene = this._gltf.scenes[this._gltf.scene || 0];
  433. var nodeIndices = scene.nodes;
  434. this._traverseNodes(nodeIndices, function (node, index, parentNode) {
  435. node.index = index;
  436. node.parent = parentNode;
  437. return true;
  438. });
  439. if (nodeNames) {
  440. if (!(nodeNames instanceof Array)) {
  441. nodeNames = [nodeNames];
  442. }
  443. var filteredNodeIndices = new Array();
  444. this._traverseNodes(nodeIndices, function (node) {
  445. if (nodeNames.indexOf(node.name) === -1) {
  446. return true;
  447. }
  448. filteredNodeIndices.push(node.index);
  449. return false;
  450. });
  451. nodeIndices = filteredNodeIndices;
  452. }
  453. this._traverseNodes(nodeIndices, function (node) { return _this._loadSkin(node); });
  454. this._traverseNodes(nodeIndices, function (node) { return _this._loadMesh(node); });
  455. };
  456. GLTFLoader.prototype._loadSkin = function (node) {
  457. var _this = this;
  458. if (node.skin !== undefined) {
  459. var skin = this._gltf.skins[node.skin];
  460. var skeletonId = "skeleton" + node.skin;
  461. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  462. skin.index = node.skin;
  463. for (var i = 0; i < skin.joints.length; i++) {
  464. this._createBone(this._gltf.nodes[skin.joints[i]], skin);
  465. }
  466. if (skin.skeleton === undefined) {
  467. // TODO: handle when skeleton is not defined
  468. throw new Error("Not implemented");
  469. }
  470. if (skin.inverseBindMatrices === undefined) {
  471. // TODO: handle when inverse bind matrices are not defined
  472. throw new Error("Not implemented");
  473. }
  474. var accessor = this._gltf.accessors[skin.inverseBindMatrices];
  475. this._loadAccessorAsync(accessor, function (data) {
  476. _this._traverseNode(skin.skeleton, function (node, index, parent) { return _this._updateBone(node, parent, skin, data); });
  477. });
  478. }
  479. return true;
  480. };
  481. GLTFLoader.prototype._updateBone = function (node, parentNode, skin, inverseBindMatrixData) {
  482. var jointIndex = skin.joints.indexOf(node.index);
  483. if (jointIndex === -1) {
  484. this._createBone(node, skin);
  485. }
  486. var babylonBone = node.babylonSkinToBones[skin.index];
  487. // TODO: explain the math
  488. var matrix = jointIndex === -1 ? BABYLON.Matrix.Identity() : BABYLON.Matrix.FromArray(inverseBindMatrixData, jointIndex * 16);
  489. matrix.invertToRef(matrix);
  490. if (parentNode) {
  491. babylonBone.setParent(parentNode.babylonSkinToBones[skin.index], false);
  492. matrix.multiplyToRef(babylonBone.getParent().getInvertedAbsoluteTransform(), matrix);
  493. }
  494. babylonBone.updateMatrix(matrix);
  495. return true;
  496. };
  497. GLTFLoader.prototype._createBone = function (node, skin) {
  498. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton);
  499. node.babylonSkinToBones = node.babylonSkinToBones || {};
  500. node.babylonSkinToBones[skin.index] = babylonBone;
  501. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  502. node.babylonAnimationTargets.push(babylonBone);
  503. return babylonBone;
  504. };
  505. GLTFLoader.prototype._loadMesh = function (node) {
  506. var babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  507. babylonMesh.isVisible = false;
  508. this._loadTransform(node, babylonMesh);
  509. if (node.mesh !== undefined) {
  510. var mesh = this._gltf.meshes[node.mesh];
  511. this._loadMeshData(node, mesh, babylonMesh);
  512. }
  513. babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  514. node.babylonMesh = babylonMesh;
  515. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  516. node.babylonAnimationTargets.push(node.babylonMesh);
  517. if (node.skin !== undefined) {
  518. var skin = this._gltf.skins[node.skin];
  519. babylonMesh.skeleton = skin.babylonSkeleton;
  520. }
  521. if (node.camera !== undefined) {
  522. // TODO: handle cameras
  523. }
  524. return true;
  525. };
  526. GLTFLoader.prototype._loadMeshData = function (node, mesh, babylonMesh) {
  527. var _this = this;
  528. babylonMesh.name = mesh.name || babylonMesh.name;
  529. var babylonMultiMaterial = new BABYLON.MultiMaterial(babylonMesh.name, this._babylonScene);
  530. babylonMesh.material = babylonMultiMaterial;
  531. var geometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene, null, false, babylonMesh);
  532. var vertexData = new BABYLON.VertexData();
  533. vertexData.positions = [];
  534. vertexData.indices = [];
  535. var subMeshInfos = [];
  536. var loadedPrimitives = 0;
  537. var totalPrimitives = mesh.primitives.length;
  538. var _loop_1 = function (i) {
  539. var primitive = mesh.primitives[i];
  540. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  541. // TODO: handle other primitive modes
  542. throw new Error("Not implemented");
  543. }
  544. this_1._createMorphTargets(node, mesh, primitive, babylonMesh);
  545. this_1._loadVertexDataAsync(primitive, function (subVertexData) {
  546. _this._loadMorphTargetsData(mesh, primitive, subVertexData, babylonMesh);
  547. subMeshInfos.push({
  548. materialIndex: i,
  549. verticesStart: vertexData.positions.length,
  550. verticesCount: subVertexData.positions.length,
  551. indicesStart: vertexData.indices.length,
  552. indicesCount: subVertexData.indices.length
  553. });
  554. vertexData.merge(subVertexData);
  555. if (primitive.material === undefined) {
  556. babylonMultiMaterial.subMaterials[i] = _this._getDefaultMaterial();
  557. }
  558. else {
  559. _this.loadMaterial(primitive.material, function (babylonSubMaterial) {
  560. if (_this._renderReady) {
  561. babylonSubMaterial.forceCompilation(babylonMesh, function (babylonSubMaterial) {
  562. babylonMultiMaterial.subMaterials[i] = babylonSubMaterial;
  563. });
  564. }
  565. else {
  566. babylonMultiMaterial.subMaterials[i] = babylonSubMaterial;
  567. }
  568. });
  569. }
  570. if (++loadedPrimitives === totalPrimitives) {
  571. geometry.setAllVerticesData(vertexData, false);
  572. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  573. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  574. babylonMesh.subMeshes = [];
  575. subMeshInfos.forEach(function (info) { return new BABYLON.SubMesh(info.materialIndex, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, babylonMesh); });
  576. }
  577. });
  578. };
  579. var this_1 = this;
  580. for (var i = 0; i < totalPrimitives; i++) {
  581. _loop_1(i);
  582. }
  583. };
  584. GLTFLoader.prototype._loadVertexDataAsync = function (primitive, onSuccess) {
  585. var _this = this;
  586. var attributes = primitive.attributes;
  587. if (!attributes) {
  588. this._errors.push("Primitive has no attributes");
  589. return;
  590. }
  591. var vertexData = new BABYLON.VertexData();
  592. var loadedAttributes = 0;
  593. var totalAttributes = Object.keys(attributes).length;
  594. var _loop_2 = function (semantic) {
  595. accessor = this_2._gltf.accessors[attributes[semantic]];
  596. this_2._loadAccessorAsync(accessor, function (data) {
  597. switch (semantic) {
  598. case "NORMAL":
  599. vertexData.normals = data;
  600. break;
  601. case "POSITION":
  602. vertexData.positions = data;
  603. break;
  604. case "TANGENT":
  605. vertexData.tangents = data;
  606. break;
  607. case "TEXCOORD_0":
  608. vertexData.uvs = data;
  609. break;
  610. case "TEXCOORD_1":
  611. vertexData.uvs2 = data;
  612. break;
  613. case "JOINTS_0":
  614. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  615. break;
  616. case "WEIGHTS_0":
  617. vertexData.matricesWeights = data;
  618. break;
  619. case "COLOR_0":
  620. vertexData.colors = data;
  621. break;
  622. default:
  623. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  624. break;
  625. }
  626. if (++loadedAttributes === totalAttributes) {
  627. var indicesAccessor = _this._gltf.accessors[primitive.indices];
  628. if (indicesAccessor) {
  629. _this._loadAccessorAsync(indicesAccessor, function (data) {
  630. vertexData.indices = data;
  631. onSuccess(vertexData);
  632. });
  633. }
  634. else {
  635. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  636. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  637. onSuccess(vertexData);
  638. }
  639. }
  640. });
  641. };
  642. var this_2 = this, accessor;
  643. for (var semantic in attributes) {
  644. _loop_2(semantic);
  645. }
  646. };
  647. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive, babylonMesh) {
  648. var targets = primitive.targets;
  649. if (!targets) {
  650. return;
  651. }
  652. if (!babylonMesh.morphTargetManager) {
  653. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  654. }
  655. for (var index = 0; index < targets.length; index++) {
  656. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  657. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  658. }
  659. };
  660. GLTFLoader.prototype._loadMorphTargetsData = function (mesh, primitive, vertexData, babylonMesh) {
  661. var targets = primitive.targets;
  662. if (!targets) {
  663. return;
  664. }
  665. var _loop_3 = function () {
  666. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  667. attributes = targets[index];
  668. var _loop_4 = function (semantic) {
  669. accessor = this_3._gltf.accessors[attributes[semantic]];
  670. this_3._loadAccessorAsync(accessor, function (data) {
  671. if (accessor.name) {
  672. babylonMorphTarget.name = accessor.name;
  673. }
  674. // glTF stores morph target information as deltas while babylon.js expects the final data.
  675. // As a result we have to add the original data to the delta to calculate the final data.
  676. var values = data;
  677. switch (semantic) {
  678. case "NORMAL":
  679. values.forEach(function (v, i) { return values[i] += vertexData.normals[i]; });
  680. babylonMorphTarget.setNormals(values);
  681. break;
  682. case "POSITION":
  683. values.forEach(function (v, i) { return values[i] += vertexData.positions[i]; });
  684. babylonMorphTarget.setPositions(values);
  685. break;
  686. case "TANGENT":
  687. // Tangent data for morph targets is stored as xyz delta.
  688. // The vertexData.tangent is stored as xyzw.
  689. // So we need to skip every fourth vertexData.tangent.
  690. for (var i = 0, j = 0; i < values.length; i++, j++) {
  691. values[i] += vertexData.tangents[j];
  692. if ((i + 1) % 3 == 0) {
  693. j++;
  694. }
  695. }
  696. babylonMorphTarget.setTangents(values);
  697. break;
  698. default:
  699. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  700. break;
  701. }
  702. });
  703. };
  704. for (var semantic in attributes) {
  705. _loop_4(semantic);
  706. }
  707. };
  708. var this_3 = this, attributes, accessor;
  709. for (var index = 0; index < targets.length; index++) {
  710. _loop_3();
  711. }
  712. };
  713. GLTFLoader.prototype._loadTransform = function (node, babylonMesh) {
  714. var position = BABYLON.Vector3.Zero();
  715. var rotation = BABYLON.Quaternion.Identity();
  716. var scaling = BABYLON.Vector3.One();
  717. if (node.matrix) {
  718. var mat = BABYLON.Matrix.FromArray(node.matrix);
  719. mat.decompose(scaling, rotation, position);
  720. }
  721. else {
  722. if (node.translation)
  723. position = BABYLON.Vector3.FromArray(node.translation);
  724. if (node.rotation)
  725. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  726. if (node.scale)
  727. scaling = BABYLON.Vector3.FromArray(node.scale);
  728. }
  729. babylonMesh.position = position;
  730. babylonMesh.rotationQuaternion = rotation;
  731. babylonMesh.scaling = scaling;
  732. };
  733. GLTFLoader.prototype._traverseNodes = function (indices, action, parentNode) {
  734. if (parentNode === void 0) { parentNode = null; }
  735. for (var i = 0; i < indices.length; i++) {
  736. this._traverseNode(indices[i], action, parentNode);
  737. }
  738. };
  739. GLTFLoader.prototype._traverseNode = function (index, action, parentNode) {
  740. if (parentNode === void 0) { parentNode = null; }
  741. var node = this._gltf.nodes[index];
  742. if (!action(node, index, parentNode)) {
  743. return;
  744. }
  745. if (node.children) {
  746. for (var i = 0; i < node.children.length; i++) {
  747. this._traverseNode(node.children[i], action, node);
  748. }
  749. }
  750. };
  751. GLTFLoader.prototype._loadAnimations = function () {
  752. var animations = this._gltf.animations;
  753. if (!animations || animations.length === 0) {
  754. return;
  755. }
  756. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  757. var animation = animations[animationIndex];
  758. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  759. this._loadAnimationChannel(animation, animationIndex, channelIndex);
  760. }
  761. }
  762. };
  763. GLTFLoader.prototype._loadAnimationChannel = function (animation, animationIndex, channelIndex) {
  764. var channel = animation.channels[channelIndex];
  765. var samplerIndex = channel.sampler;
  766. var sampler = animation.samplers[samplerIndex];
  767. var targetNode = this._gltf.nodes[channel.target.node];
  768. if (!targetNode) {
  769. BABYLON.Tools.Warn("Animation channel target node (" + channel.target.node + ") does not exist");
  770. return;
  771. }
  772. var targetPath = {
  773. "translation": "position",
  774. "rotation": "rotationQuaternion",
  775. "scale": "scaling",
  776. "weights": "influence"
  777. }[channel.target.path];
  778. if (!targetPath) {
  779. BABYLON.Tools.Warn("Animation channel target path '" + channel.target.path + "' is not valid");
  780. return;
  781. }
  782. var animationType = {
  783. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  784. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  785. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  786. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  787. }[targetPath];
  788. var inputData;
  789. var outputData;
  790. var checkSuccess = function () {
  791. if (!inputData || !outputData) {
  792. return;
  793. }
  794. var outputBufferOffset = 0;
  795. var getNextOutputValue = {
  796. "position": function () {
  797. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  798. outputBufferOffset += 3;
  799. return value;
  800. },
  801. "rotationQuaternion": function () {
  802. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  803. outputBufferOffset += 4;
  804. return value;
  805. },
  806. "scaling": function () {
  807. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  808. outputBufferOffset += 3;
  809. return value;
  810. },
  811. "influence": function () {
  812. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  813. var value = new Array(numTargets);
  814. for (var i = 0; i < numTargets; i++) {
  815. value[i] = outputData[outputBufferOffset++];
  816. }
  817. return value;
  818. },
  819. }[targetPath];
  820. var getNextKey = {
  821. "LINEAR": function (frameIndex) { return ({
  822. frame: inputData[frameIndex],
  823. value: getNextOutputValue()
  824. }); },
  825. "CUBICSPLINE": function (frameIndex) { return ({
  826. frame: inputData[frameIndex],
  827. inTangent: getNextOutputValue(),
  828. value: getNextOutputValue(),
  829. outTangent: getNextOutputValue()
  830. }); },
  831. }[sampler.interpolation];
  832. var keys = new Array(inputData.length);
  833. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  834. keys[frameIndex] = getNextKey(frameIndex);
  835. }
  836. animation.targets = animation.targets || [];
  837. if (targetPath === "influence") {
  838. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  839. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  840. var morphTarget = morphTargetManager.getTarget(targetIndex);
  841. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  842. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  843. babylonAnimation.setKeys(keys.map(function (key) { return ({
  844. frame: key.frame,
  845. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  846. value: key.value[targetIndex],
  847. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  848. }); }));
  849. morphTarget.animations.push(babylonAnimation);
  850. animation.targets.push(morphTarget);
  851. }
  852. }
  853. else {
  854. var animationName = animation.name || "anim" + animationIndex;
  855. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  856. babylonAnimation.setKeys(keys);
  857. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  858. var target = targetNode.babylonAnimationTargets[i];
  859. target.animations.push(babylonAnimation.clone());
  860. animation.targets.push(target);
  861. }
  862. }
  863. };
  864. this._loadAccessorAsync(this._gltf.accessors[sampler.input], function (data) {
  865. inputData = data;
  866. checkSuccess();
  867. });
  868. this._loadAccessorAsync(this._gltf.accessors[sampler.output], function (data) {
  869. outputData = data;
  870. checkSuccess();
  871. });
  872. };
  873. GLTFLoader.prototype._loadBufferAsync = function (index, onSuccess) {
  874. var _this = this;
  875. var buffer = this._gltf.buffers[index];
  876. this.addPendingData(buffer);
  877. if (buffer.loadedData) {
  878. setTimeout(function () {
  879. onSuccess(buffer.loadedData);
  880. _this.removePendingData(buffer);
  881. });
  882. }
  883. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  884. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  885. buffer.loadedData = new Uint8Array(data);
  886. setTimeout(function () {
  887. onSuccess(buffer.loadedData);
  888. _this.removePendingData(buffer);
  889. });
  890. }
  891. else if (buffer.loadedObservable) {
  892. buffer.loadedObservable.add(function (buffer) {
  893. onSuccess(buffer.loadedData);
  894. _this.removePendingData(buffer);
  895. });
  896. }
  897. else {
  898. buffer.loadedObservable = new BABYLON.Observable();
  899. buffer.loadedObservable.add(function (buffer) {
  900. onSuccess(buffer.loadedData);
  901. _this.removePendingData(buffer);
  902. });
  903. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  904. buffer.loadedData = new Uint8Array(data);
  905. buffer.loadedObservable.notifyObservers(buffer);
  906. buffer.loadedObservable = null;
  907. }, null, null, true, function (request) {
  908. _this._errors.push("Failed to load file '" + buffer.uri + "': " + request.statusText + "(" + request.status + ")");
  909. _this.removePendingData(buffer);
  910. });
  911. }
  912. };
  913. GLTFLoader.prototype._loadBufferViewAsync = function (bufferView, byteOffset, byteLength, componentType, onSuccess) {
  914. var _this = this;
  915. byteOffset += (bufferView.byteOffset || 0);
  916. this._loadBufferAsync(bufferView.buffer, function (bufferData) {
  917. if (byteOffset + byteLength > bufferData.byteLength) {
  918. _this._errors.push("Buffer access is out of range");
  919. return;
  920. }
  921. var buffer = bufferData.buffer;
  922. byteOffset += bufferData.byteOffset;
  923. var bufferViewData;
  924. switch (componentType) {
  925. case GLTF2.EComponentType.BYTE:
  926. bufferViewData = new Int8Array(buffer, byteOffset, byteLength);
  927. break;
  928. case GLTF2.EComponentType.UNSIGNED_BYTE:
  929. bufferViewData = new Uint8Array(buffer, byteOffset, byteLength);
  930. break;
  931. case GLTF2.EComponentType.SHORT:
  932. bufferViewData = new Int16Array(buffer, byteOffset, byteLength);
  933. break;
  934. case GLTF2.EComponentType.UNSIGNED_SHORT:
  935. bufferViewData = new Uint16Array(buffer, byteOffset, byteLength);
  936. break;
  937. case GLTF2.EComponentType.UNSIGNED_INT:
  938. bufferViewData = new Uint32Array(buffer, byteOffset, byteLength);
  939. break;
  940. case GLTF2.EComponentType.FLOAT:
  941. bufferViewData = new Float32Array(buffer, byteOffset, byteLength);
  942. break;
  943. default:
  944. _this._errors.push("Invalid component type (" + componentType + ")");
  945. return;
  946. }
  947. onSuccess(bufferViewData);
  948. });
  949. };
  950. GLTFLoader.prototype._loadAccessorAsync = function (accessor, onSuccess) {
  951. var bufferView = this._gltf.bufferViews[accessor.bufferView];
  952. var byteOffset = accessor.byteOffset || 0;
  953. var byteLength = accessor.count * GLTF2.GLTFUtils.GetByteStrideFromType(accessor);
  954. this._loadBufferViewAsync(bufferView, byteOffset, byteLength, accessor.componentType, onSuccess);
  955. };
  956. GLTFLoader.prototype.addPendingData = function (data) {
  957. if (!this._renderReady) {
  958. this._renderPendingCount++;
  959. }
  960. this.addLoaderPendingData(data);
  961. };
  962. GLTFLoader.prototype.removePendingData = function (data) {
  963. if (!this._renderReady) {
  964. if (--this._renderPendingCount === 0) {
  965. this._renderReady = true;
  966. this._onRenderReady();
  967. }
  968. }
  969. this.removeLoaderPendingData(data);
  970. };
  971. GLTFLoader.prototype.addLoaderPendingData = function (data) {
  972. this._loaderPendingCount++;
  973. };
  974. GLTFLoader.prototype.removeLoaderPendingData = function (data) {
  975. if (--this._loaderPendingCount === 0) {
  976. this._onLoaderComplete();
  977. }
  978. };
  979. GLTFLoader.prototype._getDefaultMaterial = function () {
  980. if (!this._defaultMaterial) {
  981. var id = "__gltf_default";
  982. var material = this._babylonScene.getMaterialByName(id);
  983. if (!material) {
  984. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  985. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  986. material.metallic = 1;
  987. material.roughness = 1;
  988. }
  989. this._defaultMaterial = material;
  990. }
  991. return this._defaultMaterial;
  992. };
  993. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (material) {
  994. // Ensure metallic workflow
  995. material.babylonMaterial.metallic = 1;
  996. material.babylonMaterial.roughness = 1;
  997. var properties = material.pbrMetallicRoughness;
  998. if (!properties) {
  999. return;
  1000. }
  1001. material.babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  1002. material.babylonMaterial.metallic = properties.metallicFactor === undefined ? 1 : properties.metallicFactor;
  1003. material.babylonMaterial.roughness = properties.roughnessFactor === undefined ? 1 : properties.roughnessFactor;
  1004. if (properties.baseColorTexture) {
  1005. material.babylonMaterial.albedoTexture = this.loadTexture(properties.baseColorTexture);
  1006. this.loadMaterialAlphaProperties(material);
  1007. }
  1008. if (properties.metallicRoughnessTexture) {
  1009. material.babylonMaterial.metallicTexture = this.loadTexture(properties.metallicRoughnessTexture);
  1010. material.babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1011. material.babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1012. material.babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1013. }
  1014. };
  1015. GLTFLoader.prototype.loadMaterial = function (index, assign) {
  1016. var material = this._gltf.materials[index];
  1017. material.index = index;
  1018. if (material.babylonMaterial) {
  1019. assign(material.babylonMaterial);
  1020. return;
  1021. }
  1022. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, material, assign)) {
  1023. return;
  1024. }
  1025. this.createPbrMaterial(material);
  1026. this.loadMaterialBaseProperties(material);
  1027. this._loadMaterialMetallicRoughnessProperties(material);
  1028. assign(material.babylonMaterial);
  1029. };
  1030. GLTFLoader.prototype.createPbrMaterial = function (material) {
  1031. material.babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  1032. material.babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1033. material.babylonMaterial.useScalarInLinearSpace = true;
  1034. };
  1035. GLTFLoader.prototype.loadMaterialBaseProperties = function (material) {
  1036. material.babylonMaterial.useEmissiveAsIllumination = (material.emissiveFactor || material.emissiveTexture) ? true : false;
  1037. material.babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  1038. if (material.doubleSided) {
  1039. material.babylonMaterial.backFaceCulling = false;
  1040. material.babylonMaterial.twoSidedLighting = true;
  1041. }
  1042. if (material.normalTexture) {
  1043. material.babylonMaterial.bumpTexture = this.loadTexture(material.normalTexture);
  1044. if (material.normalTexture.scale !== undefined) {
  1045. material.babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1046. }
  1047. }
  1048. if (material.occlusionTexture) {
  1049. material.babylonMaterial.ambientTexture = this.loadTexture(material.occlusionTexture);
  1050. material.babylonMaterial.useAmbientInGrayScale = true;
  1051. if (material.occlusionTexture.strength !== undefined) {
  1052. material.babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1053. }
  1054. }
  1055. if (material.emissiveTexture) {
  1056. material.babylonMaterial.emissiveTexture = this.loadTexture(material.emissiveTexture);
  1057. }
  1058. };
  1059. GLTFLoader.prototype.loadMaterialAlphaProperties = function (material) {
  1060. var alphaMode = material.alphaMode || "OPAQUE";
  1061. switch (alphaMode) {
  1062. case "OPAQUE":
  1063. // default is opaque
  1064. break;
  1065. case "MASK":
  1066. material.babylonMaterial.albedoTexture.hasAlpha = true;
  1067. material.babylonMaterial.useAlphaFromAlbedoTexture = false;
  1068. break;
  1069. case "BLEND":
  1070. material.babylonMaterial.albedoTexture.hasAlpha = true;
  1071. material.babylonMaterial.useAlphaFromAlbedoTexture = true;
  1072. break;
  1073. default:
  1074. BABYLON.Tools.Warn("Invalid alpha mode '" + material.alphaMode + "'");
  1075. break;
  1076. }
  1077. };
  1078. GLTFLoader.prototype.loadTexture = function (textureInfo) {
  1079. var _this = this;
  1080. var texture = this._gltf.textures[textureInfo.index];
  1081. var texCoord = textureInfo.texCoord || 0;
  1082. if (!texture || texture.source === undefined) {
  1083. return null;
  1084. }
  1085. // check the cache first
  1086. var babylonTexture;
  1087. if (texture.babylonTextures) {
  1088. babylonTexture = texture.babylonTextures[texCoord];
  1089. if (!babylonTexture) {
  1090. for (var i = 0; i < texture.babylonTextures.length; i++) {
  1091. babylonTexture = texture.babylonTextures[i];
  1092. if (babylonTexture) {
  1093. babylonTexture = babylonTexture.clone();
  1094. babylonTexture.coordinatesIndex = texCoord;
  1095. break;
  1096. }
  1097. }
  1098. }
  1099. return babylonTexture;
  1100. }
  1101. var source = this._gltf.images[texture.source];
  1102. var url;
  1103. if (!source.uri) {
  1104. var bufferView = this._gltf.bufferViews[source.bufferView];
  1105. this._loadBufferViewAsync(bufferView, 0, bufferView.byteLength, GLTF2.EComponentType.UNSIGNED_BYTE, function (data) {
  1106. texture.blobURL = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  1107. texture.babylonTextures[texCoord].updateURL(texture.blobURL);
  1108. });
  1109. }
  1110. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  1111. var data = new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri));
  1112. texture.blobURL = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  1113. url = texture.blobURL;
  1114. }
  1115. else {
  1116. url = this._rootUrl + source.uri;
  1117. }
  1118. var sampler = (texture.sampler === undefined ? {} : this._gltf.samplers[texture.sampler]);
  1119. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  1120. var samplingMode = GLTF2.GLTFUtils.GetTextureFilterMode(sampler.minFilter);
  1121. this.addPendingData(texture);
  1122. var babylonTexture = new BABYLON.Texture(url, this._babylonScene, noMipMaps, false, samplingMode, function () {
  1123. _this.removePendingData(texture);
  1124. }, function () {
  1125. _this._errors.push("Failed to load texture '" + source.uri + "'");
  1126. _this.removePendingData(texture);
  1127. });
  1128. babylonTexture.coordinatesIndex = texCoord;
  1129. babylonTexture.wrapU = GLTF2.GLTFUtils.GetWrapMode(sampler.wrapS);
  1130. babylonTexture.wrapV = GLTF2.GLTFUtils.GetWrapMode(sampler.wrapT);
  1131. babylonTexture.name = texture.name;
  1132. // Cache the texture
  1133. texture.babylonTextures = texture.babylonTextures || [];
  1134. texture.babylonTextures[texCoord] = babylonTexture;
  1135. return babylonTexture;
  1136. };
  1137. return GLTFLoader;
  1138. }());
  1139. GLTFLoader.Extensions = {};
  1140. GLTF2.GLTFLoader = GLTFLoader;
  1141. BABYLON.GLTFFileLoader.GLTFLoaderV2 = new GLTFLoader();
  1142. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1143. })(BABYLON || (BABYLON = {}));
  1144. //# sourceMappingURL=babylon.glTFLoader.js.map
  1145. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1146. var BABYLON;
  1147. (function (BABYLON) {
  1148. var GLTF2;
  1149. (function (GLTF2) {
  1150. /**
  1151. * Utils functions for GLTF
  1152. */
  1153. var GLTFUtils = (function () {
  1154. function GLTFUtils() {
  1155. }
  1156. /**
  1157. * If the uri is a base64 string
  1158. * @param uri: the uri to test
  1159. */
  1160. GLTFUtils.IsBase64 = function (uri) {
  1161. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1162. };
  1163. /**
  1164. * Decode the base64 uri
  1165. * @param uri: the uri to decode
  1166. */
  1167. GLTFUtils.DecodeBase64 = function (uri) {
  1168. var decodedString = atob(uri.split(",")[1]);
  1169. var bufferLength = decodedString.length;
  1170. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1171. for (var i = 0; i < bufferLength; i++) {
  1172. bufferView[i] = decodedString.charCodeAt(i);
  1173. }
  1174. return bufferView.buffer;
  1175. };
  1176. /**
  1177. * Returns the wrap mode of the texture
  1178. * @param mode: the mode value
  1179. */
  1180. GLTFUtils.GetWrapMode = function (mode) {
  1181. switch (mode) {
  1182. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1183. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1184. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1185. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1186. }
  1187. };
  1188. /**
  1189. * Returns the byte stride giving an accessor
  1190. * @param accessor: the GLTF accessor objet
  1191. */
  1192. GLTFUtils.GetByteStrideFromType = function (accessor) {
  1193. // Needs this function since "byteStride" isn't requiered in glTF format
  1194. var type = accessor.type;
  1195. switch (type) {
  1196. case "VEC2": return 2;
  1197. case "VEC3": return 3;
  1198. case "VEC4": return 4;
  1199. case "MAT2": return 4;
  1200. case "MAT3": return 9;
  1201. case "MAT4": return 16;
  1202. default: return 1;
  1203. }
  1204. };
  1205. /**
  1206. * Returns the texture filter mode giving a mode value
  1207. * @param mode: the filter mode value
  1208. */
  1209. GLTFUtils.GetTextureFilterMode = function (mode) {
  1210. switch (mode) {
  1211. case GLTF2.ETextureMinFilter.LINEAR:
  1212. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST:
  1213. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1214. case GLTF2.ETextureMinFilter.NEAREST:
  1215. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1216. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1217. }
  1218. };
  1219. /**
  1220. * Decodes a buffer view into a string
  1221. * @param view: the buffer view
  1222. */
  1223. GLTFUtils.DecodeBufferToText = function (view) {
  1224. var result = "";
  1225. var length = view.byteLength;
  1226. for (var i = 0; i < length; ++i) {
  1227. result += String.fromCharCode(view[i]);
  1228. }
  1229. return result;
  1230. };
  1231. return GLTFUtils;
  1232. }());
  1233. GLTF2.GLTFUtils = GLTFUtils;
  1234. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1235. })(BABYLON || (BABYLON = {}));
  1236. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  1237. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1238. var BABYLON;
  1239. (function (BABYLON) {
  1240. var GLTF2;
  1241. (function (GLTF2) {
  1242. var GLTFLoaderExtension = (function () {
  1243. function GLTFLoaderExtension() {
  1244. this.enabled = true;
  1245. }
  1246. GLTFLoaderExtension.prototype.loadMaterial = function (loader, material, assign) { return false; };
  1247. GLTFLoaderExtension.LoadMaterial = function (loader, material, assign) {
  1248. return this._ApplyExtensions(function (extension) { return extension.loadMaterial(loader, material, assign); });
  1249. };
  1250. GLTFLoaderExtension._ApplyExtensions = function (action) {
  1251. var extensions = GLTFLoaderExtension._Extensions;
  1252. if (!extensions) {
  1253. return;
  1254. }
  1255. for (var i = 0; i < extensions.length; i++) {
  1256. var extension = extensions[i];
  1257. if (extension.enabled && action(extension)) {
  1258. return true;
  1259. }
  1260. }
  1261. return false;
  1262. };
  1263. return GLTFLoaderExtension;
  1264. }());
  1265. //
  1266. // Utilities
  1267. //
  1268. GLTFLoaderExtension._Extensions = [];
  1269. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  1270. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1271. })(BABYLON || (BABYLON = {}));
  1272. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  1273. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  1274. var __extends = (this && this.__extends) || (function () {
  1275. var extendStatics = Object.setPrototypeOf ||
  1276. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1277. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1278. return function (d, b) {
  1279. extendStatics(d, b);
  1280. function __() { this.constructor = d; }
  1281. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1282. };
  1283. })();
  1284. var BABYLON;
  1285. (function (BABYLON) {
  1286. var GLTF2;
  1287. (function (GLTF2) {
  1288. var Extensions;
  1289. (function (Extensions) {
  1290. var MSFTLOD = (function (_super) {
  1291. __extends(MSFTLOD, _super);
  1292. function MSFTLOD() {
  1293. return _super !== null && _super.apply(this, arguments) || this;
  1294. }
  1295. Object.defineProperty(MSFTLOD.prototype, "name", {
  1296. get: function () {
  1297. return "MSFT_lod";
  1298. },
  1299. enumerable: true,
  1300. configurable: true
  1301. });
  1302. MSFTLOD.prototype.loadMaterial = function (loader, material, assign) {
  1303. if (!material.extensions) {
  1304. return false;
  1305. }
  1306. var properties = material.extensions[this.name];
  1307. if (!properties) {
  1308. return false;
  1309. }
  1310. // Clear out the extension so that it won't get loaded again.
  1311. material.extensions[this.name] = undefined;
  1312. // Tell the loader not to clear its state until the highest LOD is loaded.
  1313. loader.addLoaderPendingData(material);
  1314. // Start with the lowest quality LOD.
  1315. var materialLODs = [material.index].concat(properties.ids);
  1316. this.loadMaterialLOD(loader, material, materialLODs, materialLODs.length - 1, assign);
  1317. return true;
  1318. };
  1319. MSFTLOD.prototype.loadMaterialLOD = function (loader, material, materialLODs, lod, assign) {
  1320. var _this = this;
  1321. loader.loadMaterial(materialLODs[lod], function (babylonMaterial) {
  1322. babylonMaterial.name += ".LOD" + lod;
  1323. assign(babylonMaterial);
  1324. // Loading is complete if this is the highest quality LOD.
  1325. if (lod === 0) {
  1326. loader.removeLoaderPendingData(material);
  1327. return;
  1328. }
  1329. // Load the next LOD when all of the textures are loaded.
  1330. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  1331. _this.loadMaterialLOD(loader, material, materialLODs, lod - 1, assign);
  1332. });
  1333. });
  1334. };
  1335. return MSFTLOD;
  1336. }(GLTF2.GLTFLoaderExtension));
  1337. Extensions.MSFTLOD = MSFTLOD;
  1338. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  1339. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  1340. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1341. })(BABYLON || (BABYLON = {}));
  1342. //# sourceMappingURL=MSFT_lod.js.map
  1343. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  1344. var __extends = (this && this.__extends) || (function () {
  1345. var extendStatics = Object.setPrototypeOf ||
  1346. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1347. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1348. return function (d, b) {
  1349. extendStatics(d, b);
  1350. function __() { this.constructor = d; }
  1351. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1352. };
  1353. })();
  1354. var BABYLON;
  1355. (function (BABYLON) {
  1356. var GLTF2;
  1357. (function (GLTF2) {
  1358. var Extensions;
  1359. (function (Extensions) {
  1360. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  1361. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  1362. function KHRMaterialsPbrSpecularGlossiness() {
  1363. return _super !== null && _super.apply(this, arguments) || this;
  1364. }
  1365. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  1366. get: function () {
  1367. return "KHR_materials_pbrSpecularGlossiness";
  1368. },
  1369. enumerable: true,
  1370. configurable: true
  1371. });
  1372. KHRMaterialsPbrSpecularGlossiness.prototype.loadMaterial = function (loader, material, assign) {
  1373. if (!material.extensions) {
  1374. return false;
  1375. }
  1376. var properties = material.extensions[this.name];
  1377. if (!properties) {
  1378. return false;
  1379. }
  1380. loader.createPbrMaterial(material);
  1381. loader.loadMaterialBaseProperties(material);
  1382. material.babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  1383. material.babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  1384. material.babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  1385. if (properties.diffuseTexture) {
  1386. material.babylonMaterial.albedoTexture = loader.loadTexture(properties.diffuseTexture);
  1387. loader.loadMaterialAlphaProperties(material);
  1388. }
  1389. if (properties.specularGlossinessTexture) {
  1390. material.babylonMaterial.reflectivityTexture = loader.loadTexture(properties.specularGlossinessTexture);
  1391. material.babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  1392. }
  1393. assign(material.babylonMaterial);
  1394. return true;
  1395. };
  1396. return KHRMaterialsPbrSpecularGlossiness;
  1397. }(GLTF2.GLTFLoaderExtension));
  1398. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  1399. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  1400. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  1401. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1402. })(BABYLON || (BABYLON = {}));
  1403. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map