babylon.glTF2FileLoader.js 70 KB

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