babylon.glTF2FileLoader.js 63 KB

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