babylon.glTF2FileLoader.js 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  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. this.Extensions[extension.name] = extension;
  295. };
  296. GLTFLoader.LoadMaterial = function (index) {
  297. return BABYLON.GLTFFileLoader.GLTFLoaderV2._loadMaterial(index);
  298. };
  299. GLTFLoader.LoadCoreMaterial = function (index) {
  300. return BABYLON.GLTFFileLoader.GLTFLoaderV2._loadCoreMaterial(index);
  301. };
  302. GLTFLoader.LoadCommonMaterialProperties = function (material) {
  303. return BABYLON.GLTFFileLoader.GLTFLoaderV2._loadCommonMaterialProperties(material);
  304. };
  305. GLTFLoader.LoadAlphaProperties = function (material) {
  306. return BABYLON.GLTFFileLoader.GLTFLoaderV2._loadAlphaProperties(material);
  307. };
  308. GLTFLoader.LoadTexture = function (textureInfo) {
  309. return BABYLON.GLTFFileLoader.GLTFLoaderV2._loadTexture(textureInfo);
  310. };
  311. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onError) {
  312. var _this = this;
  313. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  314. var meshes = [];
  315. if (_this._gltf.nodes) {
  316. for (var i = 0; i < _this._gltf.nodes.length; i++) {
  317. var node = _this._gltf.nodes[i];
  318. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  319. meshes.push(node.babylonNode);
  320. }
  321. }
  322. }
  323. var skeletons = [];
  324. if (_this._gltf.skins) {
  325. for (var i = 0; i < _this._gltf.skins.length; i++) {
  326. var skin = _this._gltf.skins[i];
  327. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  328. skeletons.push(skin.babylonSkeleton);
  329. }
  330. }
  331. }
  332. onSuccess(meshes, null, skeletons);
  333. }, onError);
  334. };
  335. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  336. this._loadAsync(null, scene, data, rootUrl, onSuccess, onError);
  337. };
  338. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onError) {
  339. var _this = this;
  340. scene.useRightHandedSystem = true;
  341. this._clear();
  342. this._loadData(data);
  343. this._babylonScene = scene;
  344. this._rootUrl = rootUrl;
  345. this._onLoaded = function () {
  346. _this._showMeshes();
  347. _this._startFirstAnimation();
  348. if (_this._errors.length === 0) {
  349. onSuccess();
  350. }
  351. else {
  352. _this._errors.forEach(function (error) { return BABYLON.Tools.Error(error); });
  353. onError();
  354. }
  355. _this._clear();
  356. };
  357. this._addPendingData(this);
  358. this._loadScene(nodeNames);
  359. this._loadAnimations();
  360. this._removePendingData(this);
  361. };
  362. GLTFLoader.prototype._loadData = function (data) {
  363. this._gltf = data.json;
  364. var binaryBuffer;
  365. var buffers = this._gltf.buffers;
  366. if (buffers.length > 0 && buffers[0].uri === undefined) {
  367. binaryBuffer = buffers[0];
  368. }
  369. if (data.bin) {
  370. if (binaryBuffer) {
  371. if (binaryBuffer.byteLength != data.bin.byteLength) {
  372. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  373. }
  374. }
  375. else {
  376. BABYLON.Tools.Warn("Unexpected BIN chunk");
  377. }
  378. binaryBuffer.loadedData = data.bin;
  379. }
  380. };
  381. GLTFLoader.prototype._showMeshes = function () {
  382. var nodes = this._gltf.nodes;
  383. for (var i = 0; i < nodes.length; i++) {
  384. var node = nodes[i];
  385. if (node.babylonNode instanceof BABYLON.Mesh) {
  386. node.babylonNode.isVisible = true;
  387. }
  388. }
  389. };
  390. GLTFLoader.prototype._startFirstAnimation = function () {
  391. var animations = this._gltf.animations;
  392. if (!animations) {
  393. return;
  394. }
  395. var animation = animations[0];
  396. for (var i = 0; i < animation.targets.length; i++) {
  397. this._babylonScene.beginAnimation(animation.targets[i], 0, Number.MAX_VALUE, true);
  398. }
  399. };
  400. GLTFLoader.prototype._clear = function () {
  401. this._gltf = undefined;
  402. this._pendingCount = 0;
  403. this._onLoaded = undefined;
  404. this._errors = [];
  405. this._babylonScene = undefined;
  406. this._rootUrl = undefined;
  407. this._defaultMaterial = undefined;
  408. // Revoke object urls created during load
  409. if (this._gltf && this._gltf.textures) {
  410. for (var i = 0; i < this._gltf.textures.length; i++) {
  411. var texture = this._gltf.textures[i];
  412. if (texture.blobURL) {
  413. URL.revokeObjectURL(texture.blobURL);
  414. }
  415. }
  416. }
  417. };
  418. GLTFLoader.prototype._loadScene = function (nodeNames) {
  419. var _this = this;
  420. nodeNames = (nodeNames === "") ? null : nodeNames;
  421. nodeNames = (nodeNames instanceof Array) ? nodeNames : [nodeNames];
  422. var scene = this._gltf.scenes[this._gltf.scene || 0];
  423. this._traverseScene(nodeNames, scene, function (node) { return _this._loadSkin(node); });
  424. this._traverseScene(nodeNames, scene, function (node, parentNode) { return _this._loadMesh(node, parentNode); });
  425. };
  426. GLTFLoader.prototype._loadSkin = function (node) {
  427. var _this = this;
  428. if (node.babylonNode) {
  429. return false;
  430. }
  431. if (node.skin !== undefined) {
  432. var skin = this._gltf.skins[node.skin];
  433. var skeletonId = "skeleton" + node.skin;
  434. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  435. for (var i = 0; i < skin.joints.length; i++) {
  436. var jointIndex = skin.joints[i];
  437. var jointNode = this._gltf.nodes[jointIndex];
  438. jointNode.babylonNode = new BABYLON.Bone(jointNode.name || "bone" + jointIndex, skin.babylonSkeleton);
  439. }
  440. if (skin.skeleton === undefined) {
  441. // TODO: handle when skeleton is not defined
  442. throw new Error("Not implemented");
  443. }
  444. if (skin.inverseBindMatrices === undefined) {
  445. // TODO: handle when inverse bind matrices are not defined
  446. throw new Error("Not implemented");
  447. }
  448. var accessor = this._gltf.accessors[skin.inverseBindMatrices];
  449. this._loadAccessorAsync(accessor, function (data) {
  450. _this._traverseNode(null, skin.skeleton, function (node, parent) { return _this._updateBone(node, parent, skin, data); });
  451. });
  452. }
  453. return true;
  454. };
  455. GLTFLoader.prototype._updateBone = function (node, parentNode, skin, inverseBindMatrixData) {
  456. var jointIndex = skin.joints.indexOf(node.index);
  457. if (jointIndex === -1) {
  458. // TODO: handle non-joint in between two joints
  459. throw new Error("Not implemented");
  460. }
  461. var babylonBone = node.babylonNode;
  462. // TODO: explain the math
  463. var matrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, jointIndex * 16);
  464. matrix.invertToRef(matrix);
  465. if (parentNode) {
  466. babylonBone.setParent(parentNode.babylonNode, false);
  467. matrix.multiplyToRef(babylonBone.getParent().getInvertedAbsoluteTransform(), matrix);
  468. }
  469. babylonBone.updateMatrix(matrix);
  470. return true;
  471. };
  472. GLTFLoader.prototype._loadMesh = function (node, parentNode) {
  473. if (node.babylonNode) {
  474. if (node.babylonNode instanceof BABYLON.Bone) {
  475. if (node.mesh !== undefined) {
  476. // TODO: handle mesh attached to bone
  477. throw new Error("Not implemented");
  478. }
  479. }
  480. return false;
  481. }
  482. var babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  483. babylonMesh.isVisible = false;
  484. this._loadTransform(node, babylonMesh);
  485. if (node.mesh !== undefined) {
  486. var mesh = this._gltf.meshes[node.mesh];
  487. this._loadMeshData(node, mesh, babylonMesh);
  488. }
  489. babylonMesh.parent = parentNode ? parentNode.babylonNode : null;
  490. node.babylonNode = babylonMesh;
  491. if (node.skin !== undefined) {
  492. var skin = this._gltf.skins[node.skin];
  493. babylonMesh.skeleton = skin.babylonSkeleton;
  494. }
  495. if (node.camera !== undefined) {
  496. // TODO: handle cameras
  497. }
  498. return true;
  499. };
  500. GLTFLoader.prototype._loadMeshData = function (node, mesh, babylonMesh) {
  501. var _this = this;
  502. babylonMesh.name = mesh.name || babylonMesh.name;
  503. babylonMesh.subMeshes = [];
  504. var multiMaterial = new BABYLON.MultiMaterial(babylonMesh.name, this._babylonScene);
  505. babylonMesh.material = multiMaterial;
  506. var geometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene, null, false, babylonMesh);
  507. var vertexData = new BABYLON.VertexData();
  508. vertexData.positions = [];
  509. vertexData.indices = [];
  510. var primitivesLoaded = 0;
  511. var numPrimitives = mesh.primitives.length;
  512. for (var i = 0; i < numPrimitives; i++) {
  513. var primitive = mesh.primitives[i];
  514. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  515. // TODO: handle other primitive modes
  516. throw new Error("Not implemented");
  517. }
  518. this._createMorphTargets(node, mesh, primitive, babylonMesh);
  519. this._loadVertexDataAsync(primitive, function (subVertexData) {
  520. _this._loadMorphTargetsData(mesh, primitive, subVertexData, babylonMesh);
  521. var subMesh = new BABYLON.SubMesh(multiMaterial.subMaterials.length, vertexData.positions.length, subVertexData.positions.length, vertexData.indices.length, subVertexData.indices.length, babylonMesh);
  522. var subMaterial = primitive.material === undefined ? _this._getDefaultMaterial() : GLTF2.GLTFLoaderExtension.LoadMaterial(primitive.material);
  523. multiMaterial.subMaterials.push(subMaterial);
  524. vertexData.merge(subVertexData);
  525. if (++primitivesLoaded === numPrimitives) {
  526. geometry.setAllVerticesData(vertexData, false);
  527. }
  528. });
  529. }
  530. };
  531. GLTFLoader.prototype._loadVertexDataAsync = function (primitive, onSuccess) {
  532. var _this = this;
  533. var attributes = primitive.attributes;
  534. if (!attributes) {
  535. this._errors.push("Primitive has no attributes");
  536. return;
  537. }
  538. var vertexData = new BABYLON.VertexData();
  539. var loadedAttributes = 0;
  540. var numAttributes = Object.keys(attributes).length;
  541. var _loop_1 = function (semantic) {
  542. accessor = this_1._gltf.accessors[attributes[semantic]];
  543. this_1._loadAccessorAsync(accessor, function (data) {
  544. switch (semantic) {
  545. case "NORMAL":
  546. vertexData.normals = data;
  547. break;
  548. case "POSITION":
  549. vertexData.positions = data;
  550. break;
  551. case "TANGENT":
  552. vertexData.tangents = data;
  553. break;
  554. case "TEXCOORD_0":
  555. vertexData.uvs = data;
  556. break;
  557. case "TEXCOORD_1":
  558. vertexData.uvs2 = data;
  559. break;
  560. case "JOINTS_0":
  561. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  562. break;
  563. case "WEIGHTS_0":
  564. vertexData.matricesWeights = data;
  565. break;
  566. case "COLOR_0":
  567. vertexData.colors = data;
  568. break;
  569. default:
  570. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  571. break;
  572. }
  573. if (++loadedAttributes === numAttributes) {
  574. var indicesAccessor = _this._gltf.accessors[primitive.indices];
  575. if (indicesAccessor) {
  576. _this._loadAccessorAsync(indicesAccessor, function (data) {
  577. vertexData.indices = data;
  578. onSuccess(vertexData);
  579. });
  580. }
  581. else {
  582. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  583. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  584. onSuccess(vertexData);
  585. }
  586. }
  587. });
  588. };
  589. var this_1 = this, accessor;
  590. for (var semantic in attributes) {
  591. _loop_1(semantic);
  592. }
  593. };
  594. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive, babylonMesh) {
  595. var targets = primitive.targets;
  596. if (!targets) {
  597. return;
  598. }
  599. if (!babylonMesh.morphTargetManager) {
  600. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  601. }
  602. for (var index = 0; index < targets.length; index++) {
  603. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  604. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  605. }
  606. };
  607. GLTFLoader.prototype._loadMorphTargetsData = function (mesh, primitive, vertexData, babylonMesh) {
  608. var targets = primitive.targets;
  609. if (!targets) {
  610. return;
  611. }
  612. var _loop_2 = function () {
  613. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  614. attributes = targets[index];
  615. var _loop_3 = function (semantic) {
  616. accessor = this_2._gltf.accessors[attributes[semantic]];
  617. this_2._loadAccessorAsync(accessor, function (data) {
  618. if (accessor.name) {
  619. babylonMorphTarget.name = accessor.name;
  620. }
  621. // glTF stores morph target information as deltas while babylon.js expects the final data.
  622. // As a result we have to add the original data to the delta to calculate the final data.
  623. var values = data;
  624. switch (semantic) {
  625. case "NORMAL":
  626. values.forEach(function (v, i) { return values[i] += vertexData.normals[i]; });
  627. babylonMorphTarget.setNormals(values);
  628. break;
  629. case "POSITION":
  630. values.forEach(function (v, i) { return values[i] += vertexData.positions[i]; });
  631. babylonMorphTarget.setPositions(values);
  632. break;
  633. case "TANGENT":
  634. // Tangent data for morph targets is stored as xyz delta.
  635. // The vertexData.tangent is stored as xyzw.
  636. // So we need to skip every fourth vertexData.tangent.
  637. for (var i = 0, j = 0; i < values.length; i++, j++) {
  638. values[i] += vertexData.tangents[j];
  639. if ((i + 1) % 3 == 0) {
  640. j++;
  641. }
  642. }
  643. babylonMorphTarget.setTangents(values);
  644. break;
  645. default:
  646. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  647. break;
  648. }
  649. });
  650. };
  651. for (var semantic in attributes) {
  652. _loop_3(semantic);
  653. }
  654. };
  655. var this_2 = this, attributes, accessor;
  656. for (var index = 0; index < targets.length; index++) {
  657. _loop_2();
  658. }
  659. };
  660. GLTFLoader.prototype._loadTransform = function (node, babylonMesh) {
  661. var position = BABYLON.Vector3.Zero();
  662. var rotation = BABYLON.Quaternion.Identity();
  663. var scaling = BABYLON.Vector3.One();
  664. if (node.matrix) {
  665. var mat = BABYLON.Matrix.FromArray(node.matrix);
  666. mat.decompose(scaling, rotation, position);
  667. }
  668. else {
  669. if (node.translation)
  670. position = BABYLON.Vector3.FromArray(node.translation);
  671. if (node.rotation)
  672. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  673. if (node.scale)
  674. scaling = BABYLON.Vector3.FromArray(node.scale);
  675. }
  676. babylonMesh.position = position;
  677. babylonMesh.rotationQuaternion = rotation;
  678. babylonMesh.scaling = scaling;
  679. };
  680. GLTFLoader.prototype._traverseScene = function (nodeNames, scene, action) {
  681. var nodes = scene.nodes;
  682. if (nodes) {
  683. for (var i = 0; i < nodes.length; i++) {
  684. this._traverseNode(nodeNames, nodes[i], action);
  685. }
  686. }
  687. };
  688. GLTFLoader.prototype._traverseNode = function (nodeNames, index, action, parentNode) {
  689. if (parentNode === void 0) { parentNode = null; }
  690. var node = this._gltf.nodes[index];
  691. if (nodeNames) {
  692. if (nodeNames.indexOf(node.name)) {
  693. // load all children
  694. nodeNames = null;
  695. }
  696. else {
  697. // skip this node tree
  698. return;
  699. }
  700. }
  701. node.index = index;
  702. if (!action(node, parentNode)) {
  703. return;
  704. }
  705. if (node.children) {
  706. for (var i = 0; i < node.children.length; i++) {
  707. this._traverseNode(nodeNames, node.children[i], action, node);
  708. }
  709. }
  710. };
  711. GLTFLoader.prototype._loadAnimations = function () {
  712. var animations = this._gltf.animations;
  713. if (!animations || animations.length === 0) {
  714. return;
  715. }
  716. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  717. var animation = animations[animationIndex];
  718. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  719. this._loadAnimationChannel(animation, animationIndex, channelIndex);
  720. }
  721. }
  722. };
  723. GLTFLoader.prototype._loadAnimationChannel = function (animation, animationIndex, channelIndex) {
  724. var channel = animation.channels[channelIndex];
  725. var samplerIndex = channel.sampler;
  726. var sampler = animation.samplers[samplerIndex];
  727. var targetNode = this._gltf.nodes[channel.target.node].babylonNode;
  728. if (!targetNode) {
  729. BABYLON.Tools.Warn("Animation channel target node (" + channel.target.node + ") does not exist");
  730. return;
  731. }
  732. var targetPath = {
  733. "translation": "position",
  734. "rotation": "rotationQuaternion",
  735. "scale": "scaling",
  736. "weights": "influence"
  737. }[channel.target.path];
  738. if (!targetPath) {
  739. BABYLON.Tools.Warn("Animation channel target path '" + channel.target.path + "' is not valid");
  740. return;
  741. }
  742. var animationType = {
  743. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  744. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  745. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  746. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  747. }[targetPath];
  748. var inputData;
  749. var outputData;
  750. var checkSuccess = function () {
  751. if (!inputData || !outputData) {
  752. return;
  753. }
  754. var outputBufferOffset = 0;
  755. var getNextOutputValue = {
  756. "position": function () {
  757. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  758. outputBufferOffset += 3;
  759. return value;
  760. },
  761. "rotationQuaternion": function () {
  762. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  763. outputBufferOffset += 4;
  764. return value;
  765. },
  766. "scaling": function () {
  767. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  768. outputBufferOffset += 3;
  769. return value;
  770. },
  771. "influence": function () {
  772. var numTargets = targetNode.morphTargetManager.numTargets;
  773. var value = new Array(numTargets);
  774. for (var i = 0; i < numTargets; i++) {
  775. value[i] = outputData[outputBufferOffset++];
  776. }
  777. return value;
  778. },
  779. }[targetPath];
  780. var getNextKey = {
  781. "LINEAR": function (frameIndex) { return ({
  782. frame: inputData[frameIndex],
  783. value: getNextOutputValue()
  784. }); },
  785. "CUBICSPLINE": function (frameIndex) { return ({
  786. frame: inputData[frameIndex],
  787. inTangent: getNextOutputValue(),
  788. value: getNextOutputValue(),
  789. outTangent: getNextOutputValue()
  790. }); },
  791. }[sampler.interpolation];
  792. var keys = new Array(inputData.length);
  793. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  794. keys[frameIndex] = getNextKey(frameIndex);
  795. }
  796. animation.targets = animation.targets || [];
  797. if (targetPath === "influence") {
  798. var targetMesh = targetNode;
  799. for (var targetIndex = 0; targetIndex < targetMesh.morphTargetManager.numTargets; targetIndex++) {
  800. var morphTarget = targetMesh.morphTargetManager.getTarget(targetIndex);
  801. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  802. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  803. babylonAnimation.setKeys(keys.map(function (key) { return ({
  804. frame: key.frame,
  805. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  806. value: key.value[targetIndex],
  807. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  808. }); }));
  809. morphTarget.animations.push(babylonAnimation);
  810. animation.targets.push(morphTarget);
  811. }
  812. }
  813. else {
  814. var animationName = animation.name || "anim" + animationIndex;
  815. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  816. babylonAnimation.setKeys(keys);
  817. targetNode.animations.push(babylonAnimation);
  818. animation.targets.push(targetNode);
  819. }
  820. };
  821. this._loadAccessorAsync(this._gltf.accessors[sampler.input], function (data) {
  822. inputData = data;
  823. checkSuccess();
  824. });
  825. this._loadAccessorAsync(this._gltf.accessors[sampler.output], function (data) {
  826. outputData = data;
  827. checkSuccess();
  828. });
  829. };
  830. GLTFLoader.prototype._loadBufferAsync = function (index, onSuccess) {
  831. var _this = this;
  832. var buffer = this._gltf.buffers[index];
  833. this._addPendingData(buffer);
  834. if (buffer.loadedData) {
  835. setTimeout(function () {
  836. onSuccess(buffer.loadedData);
  837. _this._removePendingData(buffer);
  838. });
  839. }
  840. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  841. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  842. buffer.loadedData = new Uint8Array(data);
  843. setTimeout(function () {
  844. onSuccess(buffer.loadedData);
  845. _this._removePendingData(buffer);
  846. });
  847. }
  848. else if (buffer.loadedObservable) {
  849. buffer.loadedObservable.add(function (buffer) {
  850. onSuccess(buffer.loadedData);
  851. _this._removePendingData(buffer);
  852. });
  853. }
  854. else {
  855. buffer.loadedObservable = new BABYLON.Observable();
  856. buffer.loadedObservable.add(function (buffer) {
  857. onSuccess(buffer.loadedData);
  858. _this._removePendingData(buffer);
  859. });
  860. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  861. buffer.loadedData = new Uint8Array(data);
  862. buffer.loadedObservable.notifyObservers(buffer);
  863. buffer.loadedObservable = null;
  864. }, null, null, true, function (request) {
  865. _this._errors.push("Failed to load file '" + buffer.uri + "': " + request.statusText + "(" + request.status + ")");
  866. _this._removePendingData(buffer);
  867. });
  868. }
  869. };
  870. GLTFLoader.prototype._loadBufferViewAsync = function (bufferView, byteOffset, byteLength, componentType, onSuccess) {
  871. var _this = this;
  872. byteOffset += (bufferView.byteOffset || 0);
  873. this._loadBufferAsync(bufferView.buffer, function (bufferData) {
  874. if (byteOffset + byteLength > bufferData.byteLength) {
  875. _this._errors.push("Buffer access is out of range");
  876. return;
  877. }
  878. var buffer = bufferData.buffer;
  879. byteOffset += bufferData.byteOffset;
  880. var bufferViewData;
  881. switch (componentType) {
  882. case GLTF2.EComponentType.BYTE:
  883. bufferViewData = new Int8Array(buffer, byteOffset, byteLength);
  884. break;
  885. case GLTF2.EComponentType.UNSIGNED_BYTE:
  886. bufferViewData = new Uint8Array(buffer, byteOffset, byteLength);
  887. break;
  888. case GLTF2.EComponentType.SHORT:
  889. bufferViewData = new Int16Array(buffer, byteOffset, byteLength);
  890. break;
  891. case GLTF2.EComponentType.UNSIGNED_SHORT:
  892. bufferViewData = new Uint16Array(buffer, byteOffset, byteLength);
  893. break;
  894. case GLTF2.EComponentType.UNSIGNED_INT:
  895. bufferViewData = new Uint32Array(buffer, byteOffset, byteLength);
  896. break;
  897. case GLTF2.EComponentType.FLOAT:
  898. bufferViewData = new Float32Array(buffer, byteOffset, byteLength);
  899. break;
  900. default:
  901. _this._errors.push("Invalid component type (" + componentType + ")");
  902. return;
  903. }
  904. onSuccess(bufferViewData);
  905. });
  906. };
  907. GLTFLoader.prototype._loadAccessorAsync = function (accessor, onSuccess) {
  908. var bufferView = this._gltf.bufferViews[accessor.bufferView];
  909. var byteOffset = accessor.byteOffset || 0;
  910. var byteLength = accessor.count * GLTF2.GLTFUtils.GetByteStrideFromType(accessor);
  911. this._loadBufferViewAsync(bufferView, byteOffset, byteLength, accessor.componentType, onSuccess);
  912. };
  913. GLTFLoader.prototype._addPendingData = function (data) {
  914. this._pendingCount++;
  915. };
  916. GLTFLoader.prototype._removePendingData = function (data) {
  917. if (--this._pendingCount === 0) {
  918. this._onLoaded();
  919. }
  920. };
  921. GLTFLoader.prototype._getDefaultMaterial = function () {
  922. if (!this._defaultMaterial) {
  923. var id = "__gltf_default";
  924. var material = this._babylonScene.getMaterialByName(id);
  925. if (!material) {
  926. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  927. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  928. material.metallic = 1;
  929. material.roughness = 1;
  930. }
  931. this._defaultMaterial = material;
  932. }
  933. return this._defaultMaterial;
  934. };
  935. GLTFLoader.prototype._loadMaterial = function (index) {
  936. var materials = this._gltf.materials;
  937. var material = materials ? materials[index] : null;
  938. if (!material) {
  939. BABYLON.Tools.Warn("Material index (" + index + ") does not exist");
  940. return null;
  941. }
  942. material.babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + index, this._babylonScene);
  943. material.babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  944. material.babylonMaterial.useScalarInLinearSpace = true;
  945. return material;
  946. };
  947. GLTFLoader.prototype._loadCoreMaterial = function (index) {
  948. var material = this._loadMaterial(index);
  949. if (!material) {
  950. return null;
  951. }
  952. this._loadCommonMaterialProperties(material);
  953. // Ensure metallic workflow
  954. material.babylonMaterial.metallic = 1;
  955. material.babylonMaterial.roughness = 1;
  956. var properties = material.pbrMetallicRoughness;
  957. if (!properties) {
  958. return;
  959. }
  960. material.babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  961. material.babylonMaterial.metallic = properties.metallicFactor === undefined ? 1 : properties.metallicFactor;
  962. material.babylonMaterial.roughness = properties.roughnessFactor === undefined ? 1 : properties.roughnessFactor;
  963. if (properties.baseColorTexture) {
  964. material.babylonMaterial.albedoTexture = this._loadTexture(properties.baseColorTexture);
  965. this._loadAlphaProperties(material);
  966. }
  967. if (properties.metallicRoughnessTexture) {
  968. material.babylonMaterial.metallicTexture = this._loadTexture(properties.metallicRoughnessTexture);
  969. material.babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  970. material.babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  971. material.babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  972. }
  973. return material.babylonMaterial;
  974. };
  975. GLTFLoader.prototype._loadCommonMaterialProperties = function (material) {
  976. material.babylonMaterial.useEmissiveAsIllumination = (material.emissiveFactor || material.emissiveTexture) ? true : false;
  977. material.babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  978. if (material.doubleSided) {
  979. material.babylonMaterial.backFaceCulling = false;
  980. material.babylonMaterial.twoSidedLighting = true;
  981. }
  982. if (material.normalTexture) {
  983. material.babylonMaterial.bumpTexture = this._loadTexture(material.normalTexture);
  984. if (material.normalTexture.scale !== undefined) {
  985. material.babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  986. }
  987. }
  988. if (material.occlusionTexture) {
  989. material.babylonMaterial.ambientTexture = this._loadTexture(material.occlusionTexture);
  990. material.babylonMaterial.useAmbientInGrayScale = true;
  991. if (material.occlusionTexture.strength !== undefined) {
  992. material.babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  993. }
  994. }
  995. if (material.emissiveTexture) {
  996. material.babylonMaterial.emissiveTexture = this._loadTexture(material.emissiveTexture);
  997. }
  998. };
  999. GLTFLoader.prototype._loadAlphaProperties = function (material) {
  1000. var alphaMode = material.alphaMode || "OPAQUE";
  1001. switch (alphaMode) {
  1002. case "OPAQUE":
  1003. // default is opaque
  1004. break;
  1005. case "MASK":
  1006. material.babylonMaterial.albedoTexture.hasAlpha = true;
  1007. material.babylonMaterial.useAlphaFromAlbedoTexture = false;
  1008. material.babylonMaterial.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  1009. break;
  1010. case "BLEND":
  1011. material.babylonMaterial.albedoTexture.hasAlpha = true;
  1012. material.babylonMaterial.useAlphaFromAlbedoTexture = true;
  1013. material.babylonMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1014. break;
  1015. default:
  1016. BABYLON.Tools.Error("Invalid alpha mode '" + material.alphaMode + "'");
  1017. }
  1018. };
  1019. GLTFLoader.prototype._loadTexture = function (textureInfo) {
  1020. var _this = this;
  1021. var texture = this._gltf.textures[textureInfo.index];
  1022. var texCoord = textureInfo.texCoord || 0;
  1023. if (!texture || texture.source === undefined) {
  1024. return null;
  1025. }
  1026. // check the cache first
  1027. var babylonTexture;
  1028. if (texture.babylonTextures) {
  1029. babylonTexture = texture.babylonTextures[texCoord];
  1030. if (!babylonTexture) {
  1031. for (var i = 0; i < texture.babylonTextures.length; i++) {
  1032. babylonTexture = texture.babylonTextures[i];
  1033. if (babylonTexture) {
  1034. babylonTexture = babylonTexture.clone();
  1035. babylonTexture.coordinatesIndex = texCoord;
  1036. break;
  1037. }
  1038. }
  1039. }
  1040. return babylonTexture;
  1041. }
  1042. var source = this._gltf.images[texture.source];
  1043. var url;
  1044. if (!source.uri) {
  1045. var bufferView = this._gltf.bufferViews[source.bufferView];
  1046. this._loadBufferViewAsync(bufferView, 0, bufferView.byteLength, GLTF2.EComponentType.UNSIGNED_BYTE, function (data) {
  1047. texture.blobURL = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  1048. texture.babylonTextures[texCoord].updateURL(texture.blobURL);
  1049. });
  1050. }
  1051. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  1052. var data = new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri));
  1053. texture.blobURL = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  1054. url = texture.blobURL;
  1055. }
  1056. else {
  1057. url = this._rootUrl + source.uri;
  1058. }
  1059. var sampler = (texture.sampler === undefined ? {} : this._gltf.samplers[texture.sampler]);
  1060. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  1061. var samplingMode = GLTF2.GLTFUtils.GetTextureFilterMode(sampler.minFilter);
  1062. this._addPendingData(texture);
  1063. var babylonTexture = new BABYLON.Texture(url, this._babylonScene, noMipMaps, false, samplingMode, function () {
  1064. _this._removePendingData(texture);
  1065. }, function () {
  1066. _this._errors.push("Failed to load texture '" + source.uri + "'");
  1067. _this._removePendingData(texture);
  1068. });
  1069. babylonTexture.coordinatesIndex = texCoord;
  1070. babylonTexture.wrapU = GLTF2.GLTFUtils.GetWrapMode(sampler.wrapS);
  1071. babylonTexture.wrapV = GLTF2.GLTFUtils.GetWrapMode(sampler.wrapT);
  1072. babylonTexture.name = texture.name;
  1073. // Cache the texture
  1074. texture.babylonTextures = texture.babylonTextures || [];
  1075. texture.babylonTextures[texCoord] = babylonTexture;
  1076. return babylonTexture;
  1077. };
  1078. return GLTFLoader;
  1079. }());
  1080. GLTFLoader.Extensions = {};
  1081. GLTF2.GLTFLoader = GLTFLoader;
  1082. BABYLON.GLTFFileLoader.GLTFLoaderV2 = new GLTFLoader();
  1083. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1084. })(BABYLON || (BABYLON = {}));
  1085. //# sourceMappingURL=babylon.glTFLoader.js.map
  1086. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1087. var BABYLON;
  1088. (function (BABYLON) {
  1089. var GLTF2;
  1090. (function (GLTF2) {
  1091. /**
  1092. * Utils functions for GLTF
  1093. */
  1094. var GLTFUtils = (function () {
  1095. function GLTFUtils() {
  1096. }
  1097. /**
  1098. * If the uri is a base64 string
  1099. * @param uri: the uri to test
  1100. */
  1101. GLTFUtils.IsBase64 = function (uri) {
  1102. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1103. };
  1104. /**
  1105. * Decode the base64 uri
  1106. * @param uri: the uri to decode
  1107. */
  1108. GLTFUtils.DecodeBase64 = function (uri) {
  1109. var decodedString = atob(uri.split(",")[1]);
  1110. var bufferLength = decodedString.length;
  1111. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1112. for (var i = 0; i < bufferLength; i++) {
  1113. bufferView[i] = decodedString.charCodeAt(i);
  1114. }
  1115. return bufferView.buffer;
  1116. };
  1117. /**
  1118. * Returns the wrap mode of the texture
  1119. * @param mode: the mode value
  1120. */
  1121. GLTFUtils.GetWrapMode = function (mode) {
  1122. switch (mode) {
  1123. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1124. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1125. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1126. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1127. }
  1128. };
  1129. /**
  1130. * Returns the byte stride giving an accessor
  1131. * @param accessor: the GLTF accessor objet
  1132. */
  1133. GLTFUtils.GetByteStrideFromType = function (accessor) {
  1134. // Needs this function since "byteStride" isn't requiered in glTF format
  1135. var type = accessor.type;
  1136. switch (type) {
  1137. case "VEC2": return 2;
  1138. case "VEC3": return 3;
  1139. case "VEC4": return 4;
  1140. case "MAT2": return 4;
  1141. case "MAT3": return 9;
  1142. case "MAT4": return 16;
  1143. default: return 1;
  1144. }
  1145. };
  1146. /**
  1147. * Returns the texture filter mode giving a mode value
  1148. * @param mode: the filter mode value
  1149. */
  1150. GLTFUtils.GetTextureFilterMode = function (mode) {
  1151. switch (mode) {
  1152. case GLTF2.ETextureMinFilter.LINEAR:
  1153. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST:
  1154. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1155. case GLTF2.ETextureMinFilter.NEAREST:
  1156. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1157. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1158. }
  1159. };
  1160. /**
  1161. * Decodes a buffer view into a string
  1162. * @param view: the buffer view
  1163. */
  1164. GLTFUtils.DecodeBufferToText = function (view) {
  1165. var result = "";
  1166. var length = view.byteLength;
  1167. for (var i = 0; i < length; ++i) {
  1168. result += String.fromCharCode(view[i]);
  1169. }
  1170. return result;
  1171. };
  1172. return GLTFUtils;
  1173. }());
  1174. GLTF2.GLTFUtils = GLTFUtils;
  1175. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1176. })(BABYLON || (BABYLON = {}));
  1177. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  1178. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1179. var BABYLON;
  1180. (function (BABYLON) {
  1181. var GLTF2;
  1182. (function (GLTF2) {
  1183. var GLTFLoaderExtension = (function () {
  1184. function GLTFLoaderExtension(name) {
  1185. this.enabled = true;
  1186. this._name = name;
  1187. }
  1188. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  1189. get: function () {
  1190. return this._name;
  1191. },
  1192. enumerable: true,
  1193. configurable: true
  1194. });
  1195. GLTFLoaderExtension.prototype.loadMaterial = function (index) { return null; };
  1196. // ---------
  1197. // Utilities
  1198. // ---------
  1199. GLTFLoaderExtension.LoadMaterial = function (index) {
  1200. for (var extensionName in GLTF2.GLTFLoader.Extensions) {
  1201. var extension = GLTF2.GLTFLoader.Extensions[extensionName];
  1202. if (extension.enabled) {
  1203. var babylonMaterial = extension.loadMaterial(index);
  1204. if (babylonMaterial) {
  1205. return babylonMaterial;
  1206. }
  1207. }
  1208. }
  1209. return GLTF2.GLTFLoader.LoadCoreMaterial(index);
  1210. };
  1211. return GLTFLoaderExtension;
  1212. }());
  1213. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  1214. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1215. })(BABYLON || (BABYLON = {}));
  1216. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  1217. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1218. var __extends = (this && this.__extends) || (function () {
  1219. var extendStatics = Object.setPrototypeOf ||
  1220. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1221. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1222. return function (d, b) {
  1223. extendStatics(d, b);
  1224. function __() { this.constructor = d; }
  1225. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1226. };
  1227. })();
  1228. var BABYLON;
  1229. (function (BABYLON) {
  1230. var GLTF2;
  1231. (function (GLTF2) {
  1232. var GLTFMaterialsPbrSpecularGlossinessExtension = (function (_super) {
  1233. __extends(GLTFMaterialsPbrSpecularGlossinessExtension, _super);
  1234. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  1235. return _super.call(this, "KHR_materials_pbrSpecularGlossiness") || this;
  1236. }
  1237. GLTFMaterialsPbrSpecularGlossinessExtension.prototype.loadMaterial = function (index) {
  1238. var material = GLTF2.GLTFLoader.LoadMaterial(index);
  1239. if (!material || !material.extensions)
  1240. return null;
  1241. var properties = material.extensions[this.name];
  1242. if (!properties)
  1243. return null;
  1244. GLTF2.GLTFLoader.LoadCommonMaterialProperties(material);
  1245. //
  1246. // Load Factors
  1247. //
  1248. material.babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  1249. material.babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  1250. material.babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  1251. //
  1252. // Load Textures
  1253. //
  1254. if (properties.diffuseTexture) {
  1255. material.babylonMaterial.albedoTexture = GLTF2.GLTFLoader.LoadTexture(properties.diffuseTexture);
  1256. GLTF2.GLTFLoader.LoadAlphaProperties(material);
  1257. }
  1258. if (properties.specularGlossinessTexture) {
  1259. material.babylonMaterial.reflectivityTexture = GLTF2.GLTFLoader.LoadTexture(properties.specularGlossinessTexture);
  1260. material.babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  1261. }
  1262. return material.babylonMaterial;
  1263. };
  1264. return GLTFMaterialsPbrSpecularGlossinessExtension;
  1265. }(GLTF2.GLTFLoaderExtension));
  1266. GLTF2.GLTFMaterialsPbrSpecularGlossinessExtension = GLTFMaterialsPbrSpecularGlossinessExtension;
  1267. GLTF2.GLTFLoader.RegisterExtension(new GLTFMaterialsPbrSpecularGlossinessExtension());
  1268. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1269. })(BABYLON || (BABYLON = {}));
  1270. //# sourceMappingURL=babylon.glTFMaterialsPbrSpecularGlossinessExtension.js.map