babylon.glTF2FileLoader.js 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729
  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._parse = function (data) {
  30. if (data instanceof ArrayBuffer) {
  31. return GLTFFileLoader._parseBinary(data);
  32. }
  33. return {
  34. json: JSON.parse(data),
  35. bin: null
  36. };
  37. };
  38. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  39. var loaderVersion = { major: 2, minor: 0 };
  40. var asset = loaderData.json.asset || {};
  41. var version = GLTFFileLoader._parseVersion(asset.version);
  42. if (!version) {
  43. BABYLON.Tools.Error("Invalid version");
  44. return null;
  45. }
  46. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  47. if (minVersion) {
  48. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  49. BABYLON.Tools.Error("Incompatible version");
  50. return null;
  51. }
  52. }
  53. var loaders = {
  54. 1: GLTFFileLoader.GLTFLoaderV1,
  55. 2: GLTFFileLoader.GLTFLoaderV2
  56. };
  57. var loader = loaders[version.major];
  58. if (loader === undefined) {
  59. BABYLON.Tools.Error("Unsupported version");
  60. return null;
  61. }
  62. if (loader === null) {
  63. BABYLON.Tools.Error("v" + version.major + " loader is not available");
  64. return null;
  65. }
  66. return loader;
  67. };
  68. GLTFFileLoader._parseBinary = function (data) {
  69. var Binary = {
  70. Magic: 0x46546C67
  71. };
  72. var binaryReader = new BinaryReader(data);
  73. var magic = binaryReader.readUint32();
  74. if (magic !== Binary.Magic) {
  75. BABYLON.Tools.Error("Unexpected magic: " + magic);
  76. return null;
  77. }
  78. var version = binaryReader.readUint32();
  79. switch (version) {
  80. case 1: return GLTFFileLoader._parseV1(binaryReader);
  81. case 2: return GLTFFileLoader._parseV2(binaryReader);
  82. }
  83. BABYLON.Tools.Error("Unsupported version: " + version);
  84. return null;
  85. };
  86. GLTFFileLoader._parseV1 = function (binaryReader) {
  87. var ContentFormat = {
  88. JSON: 0
  89. };
  90. var length = binaryReader.readUint32();
  91. if (length != binaryReader.getLength()) {
  92. BABYLON.Tools.Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  93. return null;
  94. }
  95. var contentLength = binaryReader.readUint32();
  96. var contentFormat = binaryReader.readUint32();
  97. var content;
  98. switch (contentFormat) {
  99. case ContentFormat.JSON:
  100. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  101. break;
  102. default:
  103. BABYLON.Tools.Error("Unexpected content format: " + contentFormat);
  104. return null;
  105. }
  106. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  107. var body = binaryReader.readUint8Array(bytesRemaining);
  108. return {
  109. json: content,
  110. bin: body
  111. };
  112. };
  113. GLTFFileLoader._parseV2 = function (binaryReader) {
  114. var ChunkFormat = {
  115. JSON: 0x4E4F534A,
  116. BIN: 0x004E4942
  117. };
  118. var length = binaryReader.readUint32();
  119. if (length !== binaryReader.getLength()) {
  120. BABYLON.Tools.Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  121. return null;
  122. }
  123. // JSON chunk
  124. var chunkLength = binaryReader.readUint32();
  125. var chunkFormat = binaryReader.readUint32();
  126. if (chunkFormat !== ChunkFormat.JSON) {
  127. BABYLON.Tools.Error("First chunk format is not JSON");
  128. return null;
  129. }
  130. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  131. // Look for BIN chunk
  132. var bin = null;
  133. while (binaryReader.getPosition() < binaryReader.getLength()) {
  134. chunkLength = binaryReader.readUint32();
  135. chunkFormat = binaryReader.readUint32();
  136. switch (chunkFormat) {
  137. case ChunkFormat.JSON:
  138. BABYLON.Tools.Error("Unexpected JSON chunk");
  139. return null;
  140. case ChunkFormat.BIN:
  141. bin = binaryReader.readUint8Array(chunkLength);
  142. break;
  143. default:
  144. // ignore unrecognized chunkFormat
  145. binaryReader.skipBytes(chunkLength);
  146. break;
  147. }
  148. }
  149. return {
  150. json: json,
  151. bin: bin
  152. };
  153. };
  154. GLTFFileLoader._parseVersion = function (version) {
  155. if (!version) {
  156. return null;
  157. }
  158. var parts = version.split(".");
  159. if (parts.length === 0) {
  160. return null;
  161. }
  162. var major = parseInt(parts[0]);
  163. if (major > 1 && parts.length != 2) {
  164. return null;
  165. }
  166. var minor = parseInt(parts[1]);
  167. return {
  168. major: major,
  169. minor: parseInt(parts[0])
  170. };
  171. };
  172. GLTFFileLoader._compareVersion = function (a, b) {
  173. if (a.major > b.major)
  174. return 1;
  175. if (a.major < b.major)
  176. return -1;
  177. if (a.minor > b.minor)
  178. return 1;
  179. if (a.minor < b.minor)
  180. return -1;
  181. return 0;
  182. };
  183. GLTFFileLoader._decodeBufferToText = function (view) {
  184. var result = "";
  185. var length = view.byteLength;
  186. for (var i = 0; i < length; ++i) {
  187. result += String.fromCharCode(view[i]);
  188. }
  189. return result;
  190. };
  191. return GLTFFileLoader;
  192. }());
  193. GLTFFileLoader.GLTFLoaderV1 = null;
  194. GLTFFileLoader.GLTFLoaderV2 = null;
  195. GLTFFileLoader.HomogeneousCoordinates = false;
  196. GLTFFileLoader.IncrementalLoading = true;
  197. BABYLON.GLTFFileLoader = GLTFFileLoader;
  198. var BinaryReader = (function () {
  199. function BinaryReader(arrayBuffer) {
  200. this._arrayBuffer = arrayBuffer;
  201. this._dataView = new DataView(arrayBuffer);
  202. this._byteOffset = 0;
  203. }
  204. BinaryReader.prototype.getPosition = function () {
  205. return this._byteOffset;
  206. };
  207. BinaryReader.prototype.getLength = function () {
  208. return this._arrayBuffer.byteLength;
  209. };
  210. BinaryReader.prototype.readUint32 = function () {
  211. var value = this._dataView.getUint32(this._byteOffset, true);
  212. this._byteOffset += 4;
  213. return value;
  214. };
  215. BinaryReader.prototype.readUint8Array = function (length) {
  216. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  217. this._byteOffset += length;
  218. return value;
  219. };
  220. BinaryReader.prototype.skipBytes = function (length) {
  221. this._byteOffset += length;
  222. };
  223. return BinaryReader;
  224. }());
  225. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  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 EBufferViewTarget;
  237. (function (EBufferViewTarget) {
  238. EBufferViewTarget[EBufferViewTarget["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER";
  239. EBufferViewTarget[EBufferViewTarget["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER";
  240. })(EBufferViewTarget = GLTF2.EBufferViewTarget || (GLTF2.EBufferViewTarget = {}));
  241. var EComponentType;
  242. (function (EComponentType) {
  243. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  244. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  245. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  246. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  247. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  248. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  249. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  250. var EMeshPrimitiveMode;
  251. (function (EMeshPrimitiveMode) {
  252. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  253. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  254. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  255. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  256. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  257. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  258. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  259. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  260. var EParameterType;
  261. (function (EParameterType) {
  262. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  263. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  264. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  265. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  266. EParameterType[EParameterType["INT"] = 5124] = "INT";
  267. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  268. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  269. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  270. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  271. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  272. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  273. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  274. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  275. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  276. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  277. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  278. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  279. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  280. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  281. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  282. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  283. })(EParameterType = GLTF2.EParameterType || (GLTF2.EParameterType = {}));
  284. var ETextureMagFilter;
  285. (function (ETextureMagFilter) {
  286. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  287. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  288. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  289. var ETextureMinFilter;
  290. (function (ETextureMinFilter) {
  291. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  292. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  293. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  294. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  295. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  296. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  297. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  298. var ETextureFormat;
  299. (function (ETextureFormat) {
  300. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  301. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  302. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  303. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  304. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  305. })(ETextureFormat = GLTF2.ETextureFormat || (GLTF2.ETextureFormat = {}));
  306. var ETextureTarget;
  307. (function (ETextureTarget) {
  308. ETextureTarget[ETextureTarget["TEXTURE_2D"] = 3553] = "TEXTURE_2D";
  309. })(ETextureTarget = GLTF2.ETextureTarget || (GLTF2.ETextureTarget = {}));
  310. var ETextureType;
  311. (function (ETextureType) {
  312. ETextureType[ETextureType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  313. ETextureType[ETextureType["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5";
  314. ETextureType[ETextureType["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4";
  315. ETextureType[ETextureType["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1";
  316. })(ETextureType = GLTF2.ETextureType || (GLTF2.ETextureType = {}));
  317. var ETextureWrapMode;
  318. (function (ETextureWrapMode) {
  319. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  320. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  321. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  322. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  323. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  324. })(BABYLON || (BABYLON = {}));
  325. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  326. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  327. var BABYLON;
  328. (function (BABYLON) {
  329. var GLTF2;
  330. (function (GLTF2) {
  331. /**
  332. * Values
  333. */
  334. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  335. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  336. /**
  337. * Utils
  338. */
  339. var normalizeUVs = function (buffer) {
  340. if (!buffer) {
  341. return;
  342. }
  343. for (var i = 0; i < buffer.length / 2; i++) {
  344. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  345. }
  346. };
  347. var createStringId = function (index) {
  348. return "node" + index;
  349. };
  350. /**
  351. * Returns the animation path (glTF -> Babylon)
  352. */
  353. var getAnimationPath = function (path) {
  354. var index = glTFAnimationPaths.indexOf(path);
  355. if (index !== -1) {
  356. return babylonAnimationPaths[index];
  357. }
  358. return path;
  359. };
  360. /**
  361. * Loads and creates animations
  362. */
  363. var loadAnimations = function (runtime) {
  364. var animations = runtime.gltf.animations;
  365. if (!animations) {
  366. return;
  367. }
  368. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  369. var animation = animations[animationIndex];
  370. if (!animation || !animation.channels || !animation.samplers) {
  371. continue;
  372. }
  373. var lastAnimation = null;
  374. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  375. var channel = animation.channels[channelIndex];
  376. if (!channel) {
  377. continue;
  378. }
  379. var sampler = animation.samplers[channel.sampler];
  380. if (!sampler) {
  381. continue;
  382. }
  383. var inputData = sampler.input;
  384. var outputData = sampler.output;
  385. var bufferInput = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, runtime.gltf.accessors[inputData]);
  386. var bufferOutput = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, runtime.gltf.accessors[outputData]);
  387. var targetID = channel.target.node;
  388. var targetNode = runtime.babylonScene.getNodeByID(createStringId(targetID));
  389. if (targetNode === null) {
  390. BABYLON.Tools.Warn("Creating animation index " + animationIndex + " but cannot find node index " + targetID + " to attach to");
  391. continue;
  392. }
  393. var isBone = targetNode instanceof BABYLON.Bone;
  394. // Get target path (position, rotation or scaling)
  395. var targetPath = channel.target.path;
  396. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  397. if (targetPathIndex !== -1) {
  398. targetPath = babylonAnimationPaths[targetPathIndex];
  399. }
  400. // Determine animation type
  401. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  402. if (!isBone) {
  403. if (targetPath === "rotationQuaternion") {
  404. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  405. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  406. }
  407. else {
  408. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  409. }
  410. }
  411. // Create animation and key frames
  412. var babylonAnimation = null;
  413. var keys = [];
  414. var arrayOffset = 0;
  415. var modifyKey = false;
  416. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  417. babylonAnimation = lastAnimation;
  418. modifyKey = true;
  419. }
  420. if (!modifyKey) {
  421. var animationName = animation.name || "anim" + animationIndex;
  422. babylonAnimation = new BABYLON.Animation(animationName, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  423. }
  424. // For each frame
  425. for (var j = 0; j < bufferInput.length; j++) {
  426. var value = null;
  427. if (targetPath === "rotationQuaternion") {
  428. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  429. arrayOffset += 4;
  430. }
  431. else {
  432. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  433. arrayOffset += 3;
  434. }
  435. if (isBone) {
  436. var bone = targetNode;
  437. var translation = BABYLON.Vector3.Zero();
  438. var rotationQuaternion = new BABYLON.Quaternion();
  439. var scaling = BABYLON.Vector3.Zero();
  440. // Warning on decompose
  441. var mat = bone.getBaseMatrix();
  442. if (modifyKey) {
  443. mat = lastAnimation.getKeys()[j].value;
  444. }
  445. mat.decompose(scaling, rotationQuaternion, translation);
  446. if (targetPath === "position") {
  447. translation = value;
  448. }
  449. else if (targetPath === "rotationQuaternion") {
  450. rotationQuaternion = value;
  451. }
  452. else {
  453. scaling = value;
  454. }
  455. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  456. }
  457. if (!modifyKey) {
  458. keys.push({
  459. frame: bufferInput[j],
  460. value: value
  461. });
  462. }
  463. else {
  464. lastAnimation.getKeys()[j].value = value;
  465. }
  466. }
  467. // Finish
  468. if (!modifyKey) {
  469. babylonAnimation.setKeys(keys);
  470. targetNode.animations.push(babylonAnimation);
  471. }
  472. lastAnimation = babylonAnimation;
  473. runtime.babylonScene.stopAnimation(targetNode);
  474. runtime.babylonScene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  475. }
  476. }
  477. };
  478. /**
  479. * Returns the bones transformation matrix
  480. */
  481. var configureBoneTransformation = function (node) {
  482. var mat = null;
  483. if (node.translation || node.rotation || node.scale) {
  484. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  485. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  486. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  487. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  488. }
  489. else {
  490. mat = node.matrix ? BABYLON.Matrix.FromArray(node.matrix) : BABYLON.Matrix.Identity();
  491. }
  492. return mat;
  493. };
  494. /**
  495. * Returns the parent bone
  496. */
  497. var getParentBone = function (runtime, skin, index, newSkeleton) {
  498. // Try to find
  499. var nodeStringID = createStringId(index);
  500. for (var i = 0; i < newSkeleton.bones.length; i++) {
  501. if (newSkeleton.bones[i].id === nodeStringID) {
  502. return newSkeleton.bones[i].getParent();
  503. }
  504. }
  505. // Not found, search in gltf nodes
  506. var joints = skin.joints;
  507. for (var j = 0; j < joints.length; j++) {
  508. var parentID = joints[j];
  509. var parent = runtime.gltf.nodes[parentID];
  510. var children = parent.children;
  511. for (var i = 0; i < children.length; i++) {
  512. var childID = children[i];
  513. var child = runtime.gltf.nodes[childID];
  514. if (!nodeIsInJoints(skin, childID)) {
  515. continue;
  516. }
  517. if (childID === index) {
  518. var mat = configureBoneTransformation(parent);
  519. var bone = new BABYLON.Bone(parent.name || createStringId(parentID), newSkeleton, getParentBone(runtime, skin, parentID, newSkeleton), mat);
  520. bone.id = createStringId(parentID);
  521. return bone;
  522. }
  523. }
  524. }
  525. return null;
  526. };
  527. /**
  528. * Returns the appropriate root node
  529. */
  530. var getNodeToRoot = function (nodesToRoot, index) {
  531. for (var i = 0; i < nodesToRoot.length; i++) {
  532. var nodeToRoot = nodesToRoot[i];
  533. if (nodeToRoot.node.children) {
  534. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  535. var child = nodeToRoot.node.children[j];
  536. if (child === index) {
  537. return nodeToRoot.bone;
  538. }
  539. }
  540. }
  541. }
  542. return null;
  543. };
  544. /**
  545. * Returns the node with the node index
  546. */
  547. var getJointNode = function (runtime, index) {
  548. var node = runtime.gltf.nodes[index];
  549. if (node) {
  550. return {
  551. node: node,
  552. index: index
  553. };
  554. }
  555. return null;
  556. };
  557. /**
  558. * Checks if a nodes is in joints
  559. */
  560. var nodeIsInJoints = function (skin, index) {
  561. for (var i = 0; i < skin.joints.length; i++) {
  562. if (skin.joints[i] === index) {
  563. return true;
  564. }
  565. }
  566. return false;
  567. };
  568. /**
  569. * Fills the nodes to root for bones and builds hierarchy
  570. */
  571. var getNodesToRoot = function (runtime, newSkeleton, skin, nodesToRoot) {
  572. // Creates nodes for root
  573. for (var i = 0; i < runtime.gltf.nodes.length; i++) {
  574. var node = runtime.gltf.nodes[i];
  575. if (nodeIsInJoints(skin, i)) {
  576. continue;
  577. }
  578. // Create node to root bone
  579. var mat = configureBoneTransformation(node);
  580. var bone = new BABYLON.Bone(node.name || createStringId(i), newSkeleton, null, mat);
  581. bone.id = createStringId(i);
  582. nodesToRoot.push({ bone: bone, node: node, index: i });
  583. }
  584. // Parenting
  585. for (var i = 0; i < nodesToRoot.length; i++) {
  586. var nodeToRoot = nodesToRoot[i];
  587. var children = nodeToRoot.node.children;
  588. if (children) {
  589. for (var j = 0; j < children.length; j++) {
  590. var child = null;
  591. for (var k = 0; k < nodesToRoot.length; k++) {
  592. if (nodesToRoot[k].index === children[j]) {
  593. child = nodesToRoot[k];
  594. break;
  595. }
  596. }
  597. if (child) {
  598. child.bone._parent = nodeToRoot.bone;
  599. nodeToRoot.bone.children.push(child.bone);
  600. }
  601. }
  602. }
  603. }
  604. };
  605. /**
  606. * Imports a skeleton
  607. */
  608. var importSkeleton = function (runtime, skinNode, skin) {
  609. var name = skin.name || "skin" + skinNode.skin;
  610. var babylonSkeleton = skin.babylonSkeleton;
  611. if (!babylonSkeleton) {
  612. babylonSkeleton = new BABYLON.Skeleton(name, "skin" + skinNode.skin, runtime.babylonScene);
  613. }
  614. if (!skin.babylonSkeleton) {
  615. return babylonSkeleton;
  616. }
  617. // Matrices
  618. var accessor = runtime.gltf.accessors[skin.inverseBindMatrices];
  619. var buffer = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  620. // Find the root bones
  621. var nodesToRoot = [];
  622. var nodesToRootToAdd = [];
  623. getNodesToRoot(runtime, babylonSkeleton, skin, nodesToRoot);
  624. babylonSkeleton.bones = [];
  625. // Joints
  626. for (var i = 0; i < skin.joints.length; i++) {
  627. var jointNode = getJointNode(runtime, skin.joints[i]);
  628. var node = jointNode.node;
  629. if (!node) {
  630. BABYLON.Tools.Warn("Joint index " + skin.joints[i] + " does not exist");
  631. continue;
  632. }
  633. var index = jointNode.index;
  634. var stringID = createStringId(index);
  635. // Optimize, if the bone already exists...
  636. var existingBone = runtime.babylonScene.getBoneByID(stringID);
  637. if (existingBone) {
  638. babylonSkeleton.bones.push(existingBone);
  639. continue;
  640. }
  641. // Search for parent bone
  642. var foundBone = false;
  643. var parentBone = null;
  644. for (var j = 0; j < i; j++) {
  645. var joint = getJointNode(runtime, skin.joints[j]).node;
  646. if (!joint) {
  647. BABYLON.Tools.Warn("Joint index " + skin.joints[j] + " does not exist when looking for parent");
  648. continue;
  649. }
  650. var children = joint.children;
  651. foundBone = false;
  652. for (var k = 0; k < children.length; k++) {
  653. if (children[k] === index) {
  654. parentBone = getParentBone(runtime, skin, skin.joints[j], babylonSkeleton);
  655. foundBone = true;
  656. break;
  657. }
  658. }
  659. if (foundBone) {
  660. break;
  661. }
  662. }
  663. // Create bone
  664. var mat = configureBoneTransformation(node);
  665. if (!parentBone && nodesToRoot.length > 0) {
  666. parentBone = getNodeToRoot(nodesToRoot, index);
  667. if (parentBone) {
  668. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  669. nodesToRootToAdd.push(parentBone);
  670. }
  671. }
  672. }
  673. var bone = new BABYLON.Bone(node.name || stringID, babylonSkeleton, parentBone, mat);
  674. bone.id = stringID;
  675. }
  676. // Polish
  677. var bones = babylonSkeleton.bones;
  678. babylonSkeleton.bones = [];
  679. for (var i = 0; i < skin.joints.length; i++) {
  680. var jointNode = getJointNode(runtime, skin.joints[i]);
  681. if (!jointNode) {
  682. continue;
  683. }
  684. var jointNodeStringId = createStringId(jointNode.index);
  685. for (var j = 0; j < bones.length; j++) {
  686. if (bones[j].id === jointNodeStringId) {
  687. babylonSkeleton.bones.push(bones[j]);
  688. break;
  689. }
  690. }
  691. }
  692. babylonSkeleton.prepare();
  693. // Finish
  694. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  695. babylonSkeleton.bones.push(nodesToRootToAdd[i]);
  696. }
  697. return babylonSkeleton;
  698. };
  699. /**
  700. * Gets a material
  701. */
  702. var getMaterial = function (runtime, index) {
  703. if (index === undefined) {
  704. return GLTF2.GLTFUtils.GetDefaultMaterial(runtime);
  705. }
  706. var materials = runtime.gltf.materials;
  707. if (!materials || index < 0 || index >= materials.length) {
  708. BABYLON.Tools.Error("Invalid material index");
  709. return GLTF2.GLTFUtils.GetDefaultMaterial(runtime);
  710. }
  711. var material = runtime.gltf.materials[index].babylonMaterial;
  712. if (!material) {
  713. return GLTF2.GLTFUtils.GetDefaultMaterial(runtime);
  714. }
  715. return material;
  716. };
  717. /**
  718. * Imports a mesh and its geometries
  719. */
  720. var importMesh = function (runtime, node, mesh) {
  721. var name = mesh.name || node.name || "mesh" + node.mesh;
  722. var babylonMesh = node.babylonNode;
  723. if (!babylonMesh) {
  724. babylonMesh = new BABYLON.Mesh(name, runtime.babylonScene);
  725. }
  726. if (!node.babylonNode) {
  727. return babylonMesh;
  728. }
  729. var multiMat = new BABYLON.MultiMaterial(name, runtime.babylonScene);
  730. if (!babylonMesh.material) {
  731. babylonMesh.material = multiMat;
  732. }
  733. var vertexData = new BABYLON.VertexData();
  734. var geometry = new BABYLON.Geometry(name, runtime.babylonScene, vertexData, false, babylonMesh);
  735. var verticesStarts = [];
  736. var verticesCounts = [];
  737. var indexStarts = [];
  738. var indexCounts = [];
  739. var morphTargetManager = new BABYLON.MorphTargetManager();
  740. // Positions, normals and UVs
  741. for (var primitiveIndex = 0; primitiveIndex < mesh.primitives.length; primitiveIndex++) {
  742. // Temporary vertex data
  743. var tempVertexData = new BABYLON.VertexData();
  744. var primitive = mesh.primitives[primitiveIndex];
  745. if (primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  746. // continue;
  747. }
  748. var attributes = primitive.attributes;
  749. var accessor = null;
  750. var buffer = null;
  751. // Set positions, normal and uvs
  752. for (var semantic in attributes) {
  753. // Link accessor and buffer view
  754. accessor = runtime.gltf.accessors[attributes[semantic]];
  755. buffer = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  756. if (semantic === "NORMAL") {
  757. tempVertexData.normals = new Float32Array(buffer.length);
  758. tempVertexData.normals.set(buffer);
  759. }
  760. else if (semantic === "POSITION") {
  761. tempVertexData.positions = new Float32Array(buffer.length);
  762. tempVertexData.positions.set(buffer);
  763. verticesCounts.push(tempVertexData.positions.length);
  764. }
  765. else if (semantic === "TANGENT") {
  766. tempVertexData.tangents = new Float32Array(buffer.length);
  767. tempVertexData.tangents.set(buffer);
  768. }
  769. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  770. var channel = Number(semantic.split("_")[1]);
  771. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  772. var uvs = new Float32Array(buffer.length);
  773. uvs.set(buffer);
  774. normalizeUVs(uvs);
  775. tempVertexData.set(uvs, uvKind);
  776. }
  777. else if (semantic === "JOINT") {
  778. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  779. tempVertexData.matricesIndices.set(buffer);
  780. }
  781. else if (semantic === "WEIGHT") {
  782. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  783. tempVertexData.matricesWeights.set(buffer);
  784. }
  785. else if (semantic === "COLOR_0") {
  786. tempVertexData.colors = new Float32Array(buffer.length);
  787. tempVertexData.colors.set(buffer);
  788. }
  789. else {
  790. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  791. }
  792. }
  793. // Indices
  794. accessor = runtime.gltf.accessors[primitive.indices];
  795. if (accessor) {
  796. buffer = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  797. tempVertexData.indices = new Int32Array(buffer.length);
  798. tempVertexData.indices.set(buffer);
  799. indexCounts.push(tempVertexData.indices.length);
  800. }
  801. else {
  802. // Set indices on the fly
  803. var indices = [];
  804. for (var index = 0; index < tempVertexData.positions.length / 3; index++) {
  805. indices.push(index);
  806. }
  807. tempVertexData.indices = new Int32Array(indices);
  808. indexCounts.push(tempVertexData.indices.length);
  809. }
  810. vertexData.merge(tempVertexData);
  811. tempVertexData = undefined;
  812. // Sub material
  813. var material = getMaterial(runtime, primitive.material);
  814. multiMat.subMaterials.push(material);
  815. // Morph Targets
  816. if (primitive.targets !== undefined) {
  817. for (var targetsIndex = 0; targetsIndex < primitive.targets.length; targetsIndex++) {
  818. var target = primitive.targets[targetsIndex];
  819. var weight = 0.0;
  820. if (node.weights !== undefined) {
  821. weight = node.weights[targetsIndex];
  822. }
  823. else if (mesh.weights !== undefined) {
  824. weight = mesh.weights[targetsIndex];
  825. }
  826. var morph = new BABYLON.MorphTarget("morph" + targetsIndex, weight);
  827. for (var semantic in target) {
  828. // Link accessor and buffer view
  829. accessor = runtime.gltf.accessors[target[semantic]];
  830. buffer = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  831. if (accessor.name !== undefined) {
  832. morph.name = accessor.name;
  833. }
  834. // glTF stores morph target information as deltas
  835. // while babylon.js expects the final data.
  836. // As a result we have to add the original data to the delta to calculate
  837. // the final data.
  838. if (semantic === "NORMAL") {
  839. for (var bufferIndex = 0; bufferIndex < buffer.length; bufferIndex++) {
  840. buffer[bufferIndex] += vertexData.normals[bufferIndex];
  841. }
  842. morph.setNormals(buffer);
  843. }
  844. else if (semantic === "POSITION") {
  845. for (var bufferIndex = 0; bufferIndex < buffer.length; bufferIndex++) {
  846. buffer[bufferIndex] += vertexData.positions[bufferIndex];
  847. }
  848. morph.setPositions(buffer);
  849. }
  850. else if (semantic === "TANGENT") {
  851. // Tangent data for morph targets is stored as xyz delta.
  852. // The vertexData.tangent is stored as xyzw.
  853. // So we need to skip every fourth vertexData.tangent.
  854. for (var bufferIndex = 0, tangentsIndex = 0; bufferIndex < buffer.length; bufferIndex++, tangentsIndex++) {
  855. buffer[bufferIndex] += vertexData.tangents[tangentsIndex];
  856. if ((bufferIndex + 1) % 3 == 0) {
  857. tangentsIndex++;
  858. }
  859. }
  860. morph.setTangents(buffer);
  861. }
  862. else {
  863. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  864. }
  865. }
  866. if (morph.getPositions() !== undefined) {
  867. morphTargetManager.addTarget(morph);
  868. }
  869. else {
  870. BABYLON.Tools.Warn("Not adding morph target '" + morph.name + "' because it has no position data");
  871. }
  872. }
  873. }
  874. // Update vertices start and index start
  875. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  876. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  877. }
  878. // Apply geometry
  879. geometry.setAllVerticesData(vertexData, false);
  880. babylonMesh.computeWorldMatrix(true);
  881. // Set morph target manager after all vertices data has been processed
  882. if (morphTargetManager !== undefined && morphTargetManager.numInfluencers > 0) {
  883. babylonMesh.morphTargetManager = morphTargetManager;
  884. }
  885. // Apply submeshes
  886. babylonMesh.subMeshes = [];
  887. for (var primitiveIndex = 0; primitiveIndex < mesh.primitives.length; primitiveIndex++) {
  888. if (mesh.primitives[primitiveIndex].mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  889. //continue;
  890. }
  891. var subMesh = new BABYLON.SubMesh(primitiveIndex, verticesStarts[primitiveIndex], verticesCounts[primitiveIndex], indexStarts[primitiveIndex], indexCounts[primitiveIndex], babylonMesh, babylonMesh, true);
  892. }
  893. // Finish
  894. return babylonMesh;
  895. };
  896. /**
  897. * Configures node transformation
  898. */
  899. var configureNode = function (babylonNode, node) {
  900. var position = BABYLON.Vector3.Zero();
  901. var rotation = BABYLON.Quaternion.Identity();
  902. var scaling = new BABYLON.Vector3(1, 1, 1);
  903. if (node.matrix) {
  904. var mat = BABYLON.Matrix.FromArray(node.matrix);
  905. mat.decompose(scaling, rotation, position);
  906. }
  907. else {
  908. if (node.translation) {
  909. position = BABYLON.Vector3.FromArray(node.translation);
  910. }
  911. if (node.rotation) {
  912. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  913. }
  914. if (node.scale) {
  915. scaling = BABYLON.Vector3.FromArray(node.scale);
  916. }
  917. }
  918. babylonNode.position = position;
  919. babylonNode.rotationQuaternion = rotation;
  920. if (babylonNode instanceof BABYLON.Mesh) {
  921. var mesh = babylonNode;
  922. mesh.scaling = scaling;
  923. }
  924. };
  925. /**
  926. * Imports a node
  927. */
  928. var importNode = function (runtime, node) {
  929. var babylonNode = null;
  930. if (runtime.importOnlyMeshes && (node.skin !== undefined || node.mesh !== undefined)) {
  931. if (runtime.importMeshesNames.length > 0 && runtime.importMeshesNames.indexOf(node.name) === -1) {
  932. return null;
  933. }
  934. }
  935. // Meshes
  936. if (node.skin !== undefined) {
  937. if (node.mesh !== undefined) {
  938. var skin = runtime.gltf.skins[node.skin];
  939. var newMesh = importMesh(runtime, node, runtime.gltf.meshes[node.mesh]);
  940. var newSkeleton = importSkeleton(runtime, node, skin);
  941. if (newSkeleton) {
  942. newMesh.skeleton = newSkeleton;
  943. skin.babylonSkeleton = newSkeleton;
  944. }
  945. babylonNode = newMesh;
  946. }
  947. }
  948. else if (node.mesh !== undefined) {
  949. babylonNode = importMesh(runtime, node, runtime.gltf.meshes[node.mesh]);
  950. }
  951. else if (node.camera !== undefined && !node.babylonNode && !runtime.importOnlyMeshes) {
  952. var camera = runtime.gltf.cameras[node.camera];
  953. if (camera !== undefined) {
  954. if (camera.type === "orthographic") {
  955. var orthographicCamera = camera.orthographic;
  956. var orthoCamera = new BABYLON.FreeCamera(node.name || "camera" + node.camera, BABYLON.Vector3.Zero(), runtime.babylonScene);
  957. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  958. orthoCamera.attachControl(runtime.babylonScene.getEngine().getRenderingCanvas());
  959. babylonNode = orthoCamera;
  960. }
  961. else if (camera.type === "perspective") {
  962. var perspectiveCamera = camera.perspective;
  963. var persCamera = new BABYLON.FreeCamera(node.name || "camera" + node.camera, BABYLON.Vector3.Zero(), runtime.babylonScene);
  964. persCamera.attachControl(runtime.babylonScene.getEngine().getRenderingCanvas());
  965. if (!perspectiveCamera.aspectRatio) {
  966. perspectiveCamera.aspectRatio = runtime.babylonScene.getEngine().getRenderWidth() / runtime.babylonScene.getEngine().getRenderHeight();
  967. }
  968. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  969. persCamera.maxZ = perspectiveCamera.zfar;
  970. persCamera.minZ = perspectiveCamera.znear;
  971. }
  972. babylonNode = persCamera;
  973. }
  974. }
  975. }
  976. // Empty node
  977. if (node.babylonNode) {
  978. return node.babylonNode;
  979. }
  980. else if (babylonNode === null) {
  981. var dummy = new BABYLON.Mesh(node.name || "mesh" + node.mesh, runtime.babylonScene);
  982. node.babylonNode = dummy;
  983. babylonNode = dummy;
  984. }
  985. if (babylonNode !== null) {
  986. configureNode(babylonNode, node);
  987. babylonNode.updateCache(true);
  988. node.babylonNode = babylonNode;
  989. }
  990. return babylonNode;
  991. };
  992. /**
  993. * Traverses nodes and creates them
  994. */
  995. var traverseNodes = function (runtime, index, parent, meshIncluded) {
  996. var node = runtime.gltf.nodes[index];
  997. var newNode = null;
  998. if (runtime.importOnlyMeshes && !meshIncluded) {
  999. if (runtime.importMeshesNames.indexOf(node.name) !== -1 || runtime.importMeshesNames.length === 0) {
  1000. meshIncluded = true;
  1001. }
  1002. else {
  1003. meshIncluded = false;
  1004. }
  1005. }
  1006. else {
  1007. meshIncluded = true;
  1008. }
  1009. if (meshIncluded) {
  1010. newNode = importNode(runtime, node);
  1011. if (newNode !== null) {
  1012. newNode.id = createStringId(index);
  1013. newNode.parent = parent;
  1014. }
  1015. }
  1016. if (node.children) {
  1017. for (var i = 0; i < node.children.length; i++) {
  1018. traverseNodes(runtime, node.children[i], newNode, meshIncluded);
  1019. }
  1020. }
  1021. };
  1022. var importScene = function (runtime) {
  1023. var scene = runtime.gltf.scene || 0;
  1024. var scenes = runtime.gltf.scenes;
  1025. if (scenes) {
  1026. var nodes = scenes[scene].nodes;
  1027. for (var i = 0; i < nodes.length; i++) {
  1028. traverseNodes(runtime, nodes[i], null);
  1029. }
  1030. }
  1031. else {
  1032. for (var i = 0; i < runtime.gltf.nodes.length; i++) {
  1033. traverseNodes(runtime, i, null);
  1034. }
  1035. }
  1036. };
  1037. /**
  1038. * do stuff after buffers are loaded (e.g. hook up materials, load animations, etc.)
  1039. */
  1040. var postLoad = function (runtime) {
  1041. importScene(runtime);
  1042. // Set animations
  1043. loadAnimations(runtime);
  1044. for (var i = 0; i < runtime.babylonScene.skeletons.length; i++) {
  1045. var skeleton = runtime.babylonScene.skeletons[i];
  1046. runtime.babylonScene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1047. }
  1048. // Revoke object urls created during load
  1049. if (runtime.gltf.textures) {
  1050. for (var i = 0; i < runtime.gltf.textures.length; i++) {
  1051. var texture = runtime.gltf.textures[i];
  1052. if (texture.blobURL) {
  1053. URL.revokeObjectURL(texture.blobURL);
  1054. }
  1055. }
  1056. }
  1057. };
  1058. var BinaryReader = (function () {
  1059. function BinaryReader(arrayBuffer) {
  1060. this._arrayBuffer = arrayBuffer;
  1061. this._dataView = new DataView(arrayBuffer);
  1062. this._byteOffset = 0;
  1063. }
  1064. BinaryReader.prototype.getPosition = function () {
  1065. return this._byteOffset;
  1066. };
  1067. BinaryReader.prototype.getLength = function () {
  1068. return this._arrayBuffer.byteLength;
  1069. };
  1070. BinaryReader.prototype.readUint32 = function () {
  1071. var value = this._dataView.getUint32(this._byteOffset, true);
  1072. this._byteOffset += 4;
  1073. return value;
  1074. };
  1075. BinaryReader.prototype.readUint8Array = function (length) {
  1076. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  1077. this._byteOffset += length;
  1078. return value;
  1079. };
  1080. BinaryReader.prototype.skipBytes = function (length) {
  1081. this._byteOffset += length;
  1082. };
  1083. return BinaryReader;
  1084. }());
  1085. /**
  1086. * glTF File Loader Plugin
  1087. */
  1088. var GLTFLoader = (function () {
  1089. function GLTFLoader() {
  1090. }
  1091. GLTFLoader.RegisterExtension = function (extension) {
  1092. if (GLTFLoader.Extensions[extension.name]) {
  1093. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1094. return;
  1095. }
  1096. GLTFLoader.Extensions[extension.name] = extension;
  1097. };
  1098. GLTFLoader.LoadMaterial = function (runtime, index) {
  1099. var material = runtime.gltf.materials[index];
  1100. if (!material)
  1101. return null;
  1102. material.babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + index, runtime.babylonScene);
  1103. material.babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1104. material.babylonMaterial.useScalarInLinearSpace = true;
  1105. return material;
  1106. };
  1107. GLTFLoader.LoadMetallicRoughnessMaterialPropertiesAsync = function (runtime, material, onSuccess, onError) {
  1108. // Ensure metallic workflow
  1109. material.babylonMaterial.metallic = 1;
  1110. material.babylonMaterial.roughness = 1;
  1111. var properties = material.pbrMetallicRoughness;
  1112. if (!properties) {
  1113. onSuccess();
  1114. return;
  1115. }
  1116. //
  1117. // Load Factors
  1118. //
  1119. material.babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  1120. material.babylonMaterial.metallic = properties.metallicFactor || 1;
  1121. material.babylonMaterial.roughness = properties.roughnessFactor || 1;
  1122. //
  1123. // Load Textures
  1124. //
  1125. if (!properties.baseColorTexture && !properties.metallicRoughnessTexture) {
  1126. onSuccess();
  1127. return;
  1128. }
  1129. var checkSuccess = function () {
  1130. if ((!properties.baseColorTexture || material.babylonMaterial.albedoTexture) &&
  1131. (!properties.metallicRoughnessTexture || material.babylonMaterial.metallicTexture)) {
  1132. onSuccess();
  1133. }
  1134. };
  1135. if (properties.baseColorTexture) {
  1136. GLTFLoader.LoadTextureAsync(runtime, properties.baseColorTexture, function (texture) {
  1137. material.babylonMaterial.albedoTexture = texture;
  1138. GLTFLoader.LoadAlphaProperties(runtime, material);
  1139. checkSuccess();
  1140. }, function () {
  1141. BABYLON.Tools.Error("Failed to load base color texture");
  1142. onError();
  1143. });
  1144. }
  1145. if (properties.metallicRoughnessTexture) {
  1146. GLTFLoader.LoadTextureAsync(runtime, properties.metallicRoughnessTexture, function (texture) {
  1147. material.babylonMaterial.metallicTexture = texture;
  1148. material.babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1149. material.babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1150. material.babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1151. checkSuccess();
  1152. }, function () {
  1153. BABYLON.Tools.Error("Failed to load metallic roughness texture");
  1154. onError();
  1155. });
  1156. }
  1157. };
  1158. GLTFLoader.LoadCommonMaterialPropertiesAsync = function (runtime, material, onSuccess, onError) {
  1159. //
  1160. // Load Factors
  1161. //
  1162. material.babylonMaterial.useEmissiveAsIllumination = (material.emissiveFactor || material.emissiveTexture) ? true : false;
  1163. material.babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  1164. if (material.doubleSided) {
  1165. material.babylonMaterial.backFaceCulling = false;
  1166. material.babylonMaterial.twoSidedLighting = true;
  1167. }
  1168. //
  1169. // Load Textures
  1170. //
  1171. if (!material.normalTexture && !material.occlusionTexture && !material.emissiveTexture) {
  1172. onSuccess();
  1173. return;
  1174. }
  1175. var checkSuccess = function () {
  1176. if ((!material.normalTexture || material.babylonMaterial.bumpTexture) &&
  1177. (!material.occlusionTexture || material.babylonMaterial.ambientTexture) &&
  1178. (!material.emissiveTexture || material.babylonMaterial.emissiveTexture)) {
  1179. onSuccess();
  1180. }
  1181. };
  1182. if (material.normalTexture) {
  1183. GLTFLoader.LoadTextureAsync(runtime, material.normalTexture, function (babylonTexture) {
  1184. material.babylonMaterial.bumpTexture = babylonTexture;
  1185. if (material.normalTexture.scale !== undefined) {
  1186. material.babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1187. }
  1188. checkSuccess();
  1189. }, function () {
  1190. BABYLON.Tools.Error("Failed to load normal texture");
  1191. onError();
  1192. });
  1193. }
  1194. if (material.occlusionTexture) {
  1195. GLTFLoader.LoadTextureAsync(runtime, material.occlusionTexture, function (babylonTexture) {
  1196. material.babylonMaterial.ambientTexture = babylonTexture;
  1197. material.babylonMaterial.useAmbientInGrayScale = true;
  1198. if (material.occlusionTexture.strength !== undefined) {
  1199. material.babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1200. }
  1201. checkSuccess();
  1202. }, function () {
  1203. BABYLON.Tools.Error("Failed to load occlusion texture");
  1204. onError();
  1205. });
  1206. }
  1207. if (material.emissiveTexture) {
  1208. GLTFLoader.LoadTextureAsync(runtime, material.emissiveTexture, function (babylonTexture) {
  1209. material.babylonMaterial.emissiveTexture = babylonTexture;
  1210. checkSuccess();
  1211. }, function () {
  1212. BABYLON.Tools.Error("Failed to load emissive texture");
  1213. onError();
  1214. });
  1215. }
  1216. };
  1217. GLTFLoader.LoadAlphaProperties = function (runtime, material) {
  1218. var alphaMode = material.alphaMode || "OPAQUE";
  1219. switch (alphaMode) {
  1220. case "OPAQUE":
  1221. // default is opaque
  1222. break;
  1223. case "MASK":
  1224. material.babylonMaterial.albedoTexture.hasAlpha = true;
  1225. material.babylonMaterial.useAlphaFromAlbedoTexture = false;
  1226. material.babylonMaterial.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  1227. break;
  1228. case "BLEND":
  1229. material.babylonMaterial.albedoTexture.hasAlpha = true;
  1230. material.babylonMaterial.useAlphaFromAlbedoTexture = true;
  1231. material.babylonMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1232. break;
  1233. default:
  1234. BABYLON.Tools.Error("Invalid alpha mode '" + material.alphaMode + "'");
  1235. }
  1236. };
  1237. GLTFLoader.LoadTextureAsync = function (runtime, textureInfo, onSuccess, onError) {
  1238. var texture = runtime.gltf.textures[textureInfo.index];
  1239. var texCoord = textureInfo.texCoord || 0;
  1240. if (!texture || texture.source === undefined) {
  1241. onError();
  1242. return;
  1243. }
  1244. if (texture.babylonTextures) {
  1245. var babylonTexture = texture.babylonTextures[texCoord];
  1246. if (!babylonTexture) {
  1247. for (var i = 0; i < texture.babylonTextures.length; i++) {
  1248. babylonTexture = texture.babylonTextures[i];
  1249. if (babylonTexture) {
  1250. babylonTexture = babylonTexture.clone();
  1251. babylonTexture.coordinatesIndex = texCoord;
  1252. break;
  1253. }
  1254. }
  1255. }
  1256. onSuccess(babylonTexture);
  1257. return;
  1258. }
  1259. var source = runtime.gltf.images[texture.source];
  1260. var sourceURL = runtime.rootUrl + source.uri;
  1261. if (texture.blobURL) {
  1262. sourceURL = texture.blobURL;
  1263. }
  1264. else {
  1265. if (source.uri === undefined) {
  1266. var bufferView = runtime.gltf.bufferViews[source.bufferView];
  1267. var buffer = GLTF2.GLTFUtils.GetBufferFromBufferView(runtime, bufferView, 0, bufferView.byteLength, GLTF2.EComponentType.UNSIGNED_BYTE);
  1268. texture.blobURL = URL.createObjectURL(new Blob([buffer], { type: source.mimeType }));
  1269. sourceURL = texture.blobURL;
  1270. }
  1271. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  1272. var decodedBuffer = new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri));
  1273. texture.blobURL = URL.createObjectURL(new Blob([decodedBuffer], { type: source.mimeType }));
  1274. sourceURL = texture.blobURL;
  1275. }
  1276. }
  1277. GLTFLoader._createTextureAsync(runtime, texture, texCoord, sourceURL, onSuccess, onError);
  1278. };
  1279. GLTFLoader._createTextureAsync = function (runtime, texture, texCoord, url, onSuccess, onError) {
  1280. var sampler = texture.sampler ? runtime.gltf.samplers[texture.sampler] : {};
  1281. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  1282. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1283. var babylonTexture = new BABYLON.Texture(url, runtime.babylonScene, noMipMaps, true, samplingMode, function () {
  1284. onSuccess(babylonTexture);
  1285. }, onError);
  1286. babylonTexture.coordinatesIndex = texCoord;
  1287. babylonTexture.wrapU = GLTF2.GLTFUtils.GetWrapMode(sampler.wrapS);
  1288. babylonTexture.wrapV = GLTF2.GLTFUtils.GetWrapMode(sampler.wrapT);
  1289. babylonTexture.name = texture.name;
  1290. // Cache the texture
  1291. texture.babylonTextures = texture.babylonTextures || [];
  1292. texture.babylonTextures[texCoord] = babylonTexture;
  1293. };
  1294. /**
  1295. * Import meshes
  1296. */
  1297. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onError) {
  1298. scene.useRightHandedSystem = true;
  1299. var runtime = GLTFLoader._createRuntime(scene, data, rootUrl, true);
  1300. if (!runtime) {
  1301. onError();
  1302. return;
  1303. }
  1304. if (meshesNames === "") {
  1305. runtime.importMeshesNames = [];
  1306. }
  1307. else if (typeof meshesNames === "string") {
  1308. runtime.importMeshesNames = [meshesNames];
  1309. }
  1310. else if (meshesNames && !(meshesNames instanceof Array)) {
  1311. runtime.importMeshesNames = [meshesNames];
  1312. }
  1313. else {
  1314. runtime.importMeshesNames = [];
  1315. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1316. }
  1317. // Load scene
  1318. importScene(runtime);
  1319. var meshes = [];
  1320. var skeletons = [];
  1321. // Fill arrays of meshes and skeletons
  1322. for (var i = 0; i < runtime.gltf.nodes.length; i++) {
  1323. var node = runtime.gltf.nodes[i];
  1324. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1325. meshes.push(node.babylonNode);
  1326. }
  1327. }
  1328. for (var i = 0; i < runtime.gltf.skins.length; i++) {
  1329. var skin = runtime.gltf.skins[i];
  1330. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1331. skeletons.push(skin.babylonSkeleton);
  1332. }
  1333. }
  1334. // Load buffers, materials, etc.
  1335. GLTFLoader._loadBuffersAsync(runtime, function () {
  1336. GLTFLoader._loadMaterialsAsync(runtime, function () {
  1337. postLoad(runtime);
  1338. onSuccess(meshes, null, skeletons);
  1339. }, onError);
  1340. }, onError);
  1341. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1342. onSuccess(meshes, null, skeletons);
  1343. }
  1344. };
  1345. /**
  1346. * Load scene
  1347. */
  1348. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1349. scene.useRightHandedSystem = true;
  1350. var runtime = GLTFLoader._createRuntime(scene, data, rootUrl, false);
  1351. if (!runtime) {
  1352. onError();
  1353. return;
  1354. }
  1355. importScene(runtime);
  1356. GLTFLoader._loadBuffersAsync(runtime, function () {
  1357. GLTFLoader._loadMaterialsAsync(runtime, function () {
  1358. postLoad(runtime);
  1359. onSuccess();
  1360. }, onError);
  1361. }, onError);
  1362. };
  1363. GLTFLoader._loadBuffersAsync = function (runtime, onSuccess, onError) {
  1364. var _this = this;
  1365. if (runtime.gltf.buffers.length == 0) {
  1366. onSuccess();
  1367. return;
  1368. }
  1369. var successCount = 0;
  1370. runtime.gltf.buffers.forEach(function (buffer, index) {
  1371. _this._loadBufferAsync(runtime, index, function () {
  1372. if (++successCount === runtime.gltf.buffers.length) {
  1373. onSuccess();
  1374. }
  1375. }, onError);
  1376. });
  1377. };
  1378. GLTFLoader._loadBufferAsync = function (runtime, index, onSuccess, onError) {
  1379. var buffer = runtime.gltf.buffers[index];
  1380. if (buffer.uri === undefined) {
  1381. // buffer.loadedBufferView should already be set
  1382. onSuccess();
  1383. }
  1384. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  1385. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  1386. setTimeout(function () {
  1387. buffer.loadedBufferView = new Uint8Array(data);
  1388. onSuccess();
  1389. });
  1390. }
  1391. else {
  1392. BABYLON.Tools.LoadFile(runtime.rootUrl + buffer.uri, function (data) {
  1393. buffer.loadedBufferView = new Uint8Array(data);
  1394. onSuccess();
  1395. }, null, null, true, onError);
  1396. }
  1397. };
  1398. GLTFLoader._loadMaterialsAsync = function (runtime, onSuccess, onError) {
  1399. var materials = runtime.gltf.materials;
  1400. if (!materials) {
  1401. onSuccess();
  1402. return;
  1403. }
  1404. var successCount = 0;
  1405. for (var i = 0; i < materials.length; i++) {
  1406. GLTF2.GLTFLoaderExtension.LoadMaterialAsync(runtime, i, function () {
  1407. if (++successCount === materials.length) {
  1408. onSuccess();
  1409. }
  1410. }, onError);
  1411. }
  1412. };
  1413. GLTFLoader._createRuntime = function (scene, data, rootUrl, importOnlyMeshes) {
  1414. var runtime = {
  1415. gltf: data.json,
  1416. babylonScene: scene,
  1417. rootUrl: rootUrl,
  1418. importOnlyMeshes: importOnlyMeshes,
  1419. };
  1420. var binaryBuffer;
  1421. var buffers = runtime.gltf.buffers;
  1422. if (buffers.length > 0 && buffers[0].uri === undefined) {
  1423. binaryBuffer = buffers[0];
  1424. }
  1425. if (data.bin) {
  1426. if (!binaryBuffer) {
  1427. BABYLON.Tools.Error("Unexpected BIN chunk");
  1428. return null;
  1429. }
  1430. if (binaryBuffer.byteLength != data.bin.byteLength) {
  1431. BABYLON.Tools.Error("Binary buffer length from JSON does not match chunk length");
  1432. return null;
  1433. }
  1434. binaryBuffer.loadedBufferView = data.bin;
  1435. }
  1436. GLTF2.GLTFLoaderExtension.PostCreateRuntime(runtime);
  1437. return runtime;
  1438. };
  1439. return GLTFLoader;
  1440. }());
  1441. GLTFLoader.Extensions = {};
  1442. GLTF2.GLTFLoader = GLTFLoader;
  1443. BABYLON.GLTFFileLoader.GLTFLoaderV2 = new GLTFLoader();
  1444. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1445. })(BABYLON || (BABYLON = {}));
  1446. //# sourceMappingURL=babylon.glTFLoader.js.map
  1447. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1448. var BABYLON;
  1449. (function (BABYLON) {
  1450. var GLTF2;
  1451. (function (GLTF2) {
  1452. /**
  1453. * Utils functions for GLTF
  1454. */
  1455. var GLTFUtils = (function () {
  1456. function GLTFUtils() {
  1457. }
  1458. /**
  1459. * If the uri is a base64 string
  1460. * @param uri: the uri to test
  1461. */
  1462. GLTFUtils.IsBase64 = function (uri) {
  1463. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1464. };
  1465. /**
  1466. * Decode the base64 uri
  1467. * @param uri: the uri to decode
  1468. */
  1469. GLTFUtils.DecodeBase64 = function (uri) {
  1470. var decodedString = atob(uri.split(",")[1]);
  1471. var bufferLength = decodedString.length;
  1472. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1473. for (var i = 0; i < bufferLength; i++) {
  1474. bufferView[i] = decodedString.charCodeAt(i);
  1475. }
  1476. return bufferView.buffer;
  1477. };
  1478. /**
  1479. * Returns the wrap mode of the texture
  1480. * @param mode: the mode value
  1481. */
  1482. GLTFUtils.GetWrapMode = function (mode) {
  1483. switch (mode) {
  1484. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1485. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1486. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1487. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1488. }
  1489. };
  1490. /**
  1491. * Returns the byte stride giving an accessor
  1492. * @param accessor: the GLTF accessor objet
  1493. */
  1494. GLTFUtils.GetByteStrideFromType = function (accessor) {
  1495. // Needs this function since "byteStride" isn't requiered in glTF format
  1496. var type = accessor.type;
  1497. switch (type) {
  1498. case "VEC2": return 2;
  1499. case "VEC3": return 3;
  1500. case "VEC4": return 4;
  1501. case "MAT2": return 4;
  1502. case "MAT3": return 9;
  1503. case "MAT4": return 16;
  1504. default: return 1;
  1505. }
  1506. };
  1507. /**
  1508. * Returns the texture filter mode giving a mode value
  1509. * @param mode: the filter mode value
  1510. */
  1511. GLTFUtils.GetTextureFilterMode = function (mode) {
  1512. switch (mode) {
  1513. case GLTF2.ETextureMinFilter.LINEAR:
  1514. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST:
  1515. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1516. case GLTF2.ETextureMinFilter.NEAREST:
  1517. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1518. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1519. }
  1520. };
  1521. GLTFUtils.GetBufferFromBufferView = function (runtime, bufferView, byteOffset, byteLength, componentType) {
  1522. var byteOffset = bufferView.byteOffset + byteOffset;
  1523. var loadedBufferView = runtime.gltf.buffers[bufferView.buffer].loadedBufferView;
  1524. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  1525. throw new Error("Buffer access is out of range");
  1526. }
  1527. var buffer = loadedBufferView.buffer;
  1528. byteOffset += loadedBufferView.byteOffset;
  1529. switch (componentType) {
  1530. case GLTF2.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  1531. case GLTF2.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  1532. case GLTF2.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  1533. case GLTF2.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  1534. case GLTF2.EComponentType.UNSIGNED_INT: return new Uint32Array(buffer, byteOffset, byteLength);
  1535. default: return new Float32Array(buffer, byteOffset, byteLength);
  1536. }
  1537. };
  1538. /**
  1539. * Returns a buffer from its accessor
  1540. * @param runtime: the GLTF runtime
  1541. * @param accessor: the GLTF accessor
  1542. */
  1543. GLTFUtils.GetBufferFromAccessor = function (runtime, accessor) {
  1544. var bufferView = runtime.gltf.bufferViews[accessor.bufferView];
  1545. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  1546. return GLTFUtils.GetBufferFromBufferView(runtime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  1547. };
  1548. /**
  1549. * Decodes a buffer view into a string
  1550. * @param view: the buffer view
  1551. */
  1552. GLTFUtils.DecodeBufferToText = function (view) {
  1553. var result = "";
  1554. var length = view.byteLength;
  1555. for (var i = 0; i < length; ++i) {
  1556. result += String.fromCharCode(view[i]);
  1557. }
  1558. return result;
  1559. };
  1560. /**
  1561. * Returns the default material of gltf.
  1562. * @param scene: the Babylon.js scene
  1563. */
  1564. GLTFUtils.GetDefaultMaterial = function (runtime) {
  1565. if (!runtime.defaultMaterial) {
  1566. var material = new BABYLON.PBRMaterial("gltf_default", runtime.babylonScene);
  1567. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1568. material.metallic = 1;
  1569. material.roughness = 1;
  1570. runtime.defaultMaterial = material;
  1571. }
  1572. return runtime.defaultMaterial;
  1573. };
  1574. return GLTFUtils;
  1575. }());
  1576. GLTF2.GLTFUtils = GLTFUtils;
  1577. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1578. })(BABYLON || (BABYLON = {}));
  1579. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  1580. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1581. var BABYLON;
  1582. (function (BABYLON) {
  1583. var GLTF2;
  1584. (function (GLTF2) {
  1585. var GLTFLoaderExtension = (function () {
  1586. function GLTFLoaderExtension(name) {
  1587. this._name = name;
  1588. }
  1589. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  1590. get: function () {
  1591. return this._name;
  1592. },
  1593. enumerable: true,
  1594. configurable: true
  1595. });
  1596. GLTFLoaderExtension.prototype.postCreateRuntime = function (runtime) { };
  1597. // Return true to stop other extensions from loading materials.
  1598. GLTFLoaderExtension.prototype.loadMaterialAsync = function (runtime, index, onSuccess, onError) { return false; };
  1599. // ---------
  1600. // Utilities
  1601. // ---------
  1602. GLTFLoaderExtension.PostCreateRuntime = function (runtime) {
  1603. for (var extensionName in GLTF2.GLTFLoader.Extensions) {
  1604. var extension = GLTF2.GLTFLoader.Extensions[extensionName];
  1605. extension.postCreateRuntime(runtime);
  1606. }
  1607. };
  1608. GLTFLoaderExtension.LoadMaterialAsync = function (runtime, index, onSuccess, onError) {
  1609. for (var extensionName in GLTF2.GLTFLoader.Extensions) {
  1610. var extension = GLTF2.GLTFLoader.Extensions[extensionName];
  1611. if (extension.loadMaterialAsync(runtime, index, onSuccess, onError)) {
  1612. return;
  1613. }
  1614. }
  1615. var material = GLTF2.GLTFLoader.LoadMaterial(runtime, index);
  1616. if (!material) {
  1617. onSuccess();
  1618. return;
  1619. }
  1620. var metallicRoughnessPropertiesSuccess = false;
  1621. var commonPropertiesSuccess = false;
  1622. var checkSuccess = function () {
  1623. if (metallicRoughnessPropertiesSuccess && commonPropertiesSuccess) {
  1624. onSuccess();
  1625. }
  1626. };
  1627. GLTF2.GLTFLoader.LoadMetallicRoughnessMaterialPropertiesAsync(runtime, material, function () {
  1628. metallicRoughnessPropertiesSuccess = true;
  1629. checkSuccess();
  1630. }, onError);
  1631. GLTF2.GLTFLoader.LoadCommonMaterialPropertiesAsync(runtime, material, function () {
  1632. commonPropertiesSuccess = true;
  1633. checkSuccess();
  1634. }, onError);
  1635. };
  1636. return GLTFLoaderExtension;
  1637. }());
  1638. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  1639. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1640. })(BABYLON || (BABYLON = {}));
  1641. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  1642. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1643. var __extends = (this && this.__extends) || (function () {
  1644. var extendStatics = Object.setPrototypeOf ||
  1645. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1646. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1647. return function (d, b) {
  1648. extendStatics(d, b);
  1649. function __() { this.constructor = d; }
  1650. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1651. };
  1652. })();
  1653. var BABYLON;
  1654. (function (BABYLON) {
  1655. var GLTF2;
  1656. (function (GLTF2) {
  1657. var GLTFMaterialsPbrSpecularGlossinessExtension = (function (_super) {
  1658. __extends(GLTFMaterialsPbrSpecularGlossinessExtension, _super);
  1659. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  1660. return _super.call(this, "KHR_materials_pbrSpecularGlossiness") || this;
  1661. }
  1662. GLTFMaterialsPbrSpecularGlossinessExtension.prototype.loadMaterialAsync = function (runtime, index, onSuccess, onError) {
  1663. var material = GLTF2.GLTFLoader.LoadMaterial(runtime, index);
  1664. if (!material || !material.extensions)
  1665. return false;
  1666. var properties = material.extensions[this.name];
  1667. if (!properties)
  1668. return false;
  1669. //
  1670. // Load Factors
  1671. //
  1672. material.babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  1673. material.babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  1674. material.babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  1675. //
  1676. // Load Textures
  1677. //
  1678. var commonMaterialPropertiesSuccess = false;
  1679. var checkSuccess = function () {
  1680. if ((!properties.diffuseTexture || material.babylonMaterial.albedoTexture) &&
  1681. (!properties.specularGlossinessTexture || material.babylonMaterial.reflectivityTexture) &&
  1682. commonMaterialPropertiesSuccess) {
  1683. onSuccess();
  1684. }
  1685. };
  1686. if (properties.diffuseTexture) {
  1687. GLTF2.GLTFLoader.LoadTextureAsync(runtime, properties.diffuseTexture, function (texture) {
  1688. material.babylonMaterial.albedoTexture = texture;
  1689. GLTF2.GLTFLoader.LoadAlphaProperties(runtime, material);
  1690. checkSuccess();
  1691. }, function () {
  1692. BABYLON.Tools.Warn("Failed to load diffuse texture");
  1693. onError();
  1694. });
  1695. }
  1696. if (properties.specularGlossinessTexture) {
  1697. GLTF2.GLTFLoader.LoadTextureAsync(runtime, properties.specularGlossinessTexture, function (texture) {
  1698. material.babylonMaterial.reflectivityTexture = texture;
  1699. material.babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  1700. checkSuccess();
  1701. }, function () {
  1702. BABYLON.Tools.Warn("Failed to load metallic roughness texture");
  1703. onError();
  1704. });
  1705. }
  1706. GLTF2.GLTFLoader.LoadCommonMaterialPropertiesAsync(runtime, material, function () {
  1707. commonMaterialPropertiesSuccess = true;
  1708. checkSuccess();
  1709. }, onError);
  1710. return true;
  1711. };
  1712. return GLTFMaterialsPbrSpecularGlossinessExtension;
  1713. }(GLTF2.GLTFLoaderExtension));
  1714. GLTF2.GLTFMaterialsPbrSpecularGlossinessExtension = GLTFMaterialsPbrSpecularGlossinessExtension;
  1715. GLTF2.GLTFLoader.RegisterExtension(new GLTFMaterialsPbrSpecularGlossinessExtension());
  1716. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1717. })(BABYLON || (BABYLON = {}));
  1718. //# sourceMappingURL=babylon.glTFMaterialsPbrSpecularGlossinessExtension.js.map