babylon.glTF2FileLoader.js 71 KB

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