babylon.glTF2FileLoader.js 63 KB

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