babylon.glTF2FileLoader.js 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663
  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. // Positions, normals and UVs
  740. for (var index = 0; index < mesh.primitives.length; index++) {
  741. // Temporary vertex data
  742. var tempVertexData = new BABYLON.VertexData();
  743. var primitive = mesh.primitives[index];
  744. if (primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  745. // continue;
  746. }
  747. var attributes = primitive.attributes;
  748. var accessor = null;
  749. var buffer = null;
  750. // Set positions, normal and uvs
  751. for (var semantic in attributes) {
  752. // Link accessor and buffer view
  753. accessor = runtime.gltf.accessors[attributes[semantic]];
  754. buffer = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  755. if (semantic === "NORMAL") {
  756. tempVertexData.normals = new Float32Array(buffer.length);
  757. tempVertexData.normals.set(buffer);
  758. }
  759. else if (semantic === "POSITION") {
  760. tempVertexData.positions = new Float32Array(buffer.length);
  761. tempVertexData.positions.set(buffer);
  762. verticesCounts.push(tempVertexData.positions.length);
  763. }
  764. else if (semantic === "TANGENT") {
  765. tempVertexData.tangents = new Float32Array(buffer.length);
  766. tempVertexData.tangents.set(buffer);
  767. }
  768. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  769. var channel = Number(semantic.split("_")[1]);
  770. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  771. var uvs = new Float32Array(buffer.length);
  772. uvs.set(buffer);
  773. normalizeUVs(uvs);
  774. tempVertexData.set(uvs, uvKind);
  775. }
  776. else if (semantic === "JOINT") {
  777. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  778. tempVertexData.matricesIndices.set(buffer);
  779. }
  780. else if (semantic === "WEIGHT") {
  781. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  782. tempVertexData.matricesWeights.set(buffer);
  783. }
  784. else if (semantic === "COLOR_0") {
  785. tempVertexData.colors = new Float32Array(buffer.length);
  786. tempVertexData.colors.set(buffer);
  787. }
  788. else {
  789. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  790. }
  791. }
  792. // Indices
  793. accessor = runtime.gltf.accessors[primitive.indices];
  794. if (accessor) {
  795. buffer = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  796. tempVertexData.indices = new Int32Array(buffer.length);
  797. tempVertexData.indices.set(buffer);
  798. indexCounts.push(tempVertexData.indices.length);
  799. }
  800. else {
  801. // Set indices on the fly
  802. var indices = [];
  803. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  804. indices.push(j);
  805. }
  806. tempVertexData.indices = new Int32Array(indices);
  807. indexCounts.push(tempVertexData.indices.length);
  808. }
  809. vertexData.merge(tempVertexData);
  810. tempVertexData = undefined;
  811. // Sub material
  812. var material = getMaterial(runtime, primitive.material);
  813. multiMat.subMaterials.push(material);
  814. // Update vertices start and index start
  815. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  816. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  817. }
  818. // Apply geometry
  819. geometry.setAllVerticesData(vertexData, false);
  820. babylonMesh.computeWorldMatrix(true);
  821. // Apply submeshes
  822. babylonMesh.subMeshes = [];
  823. for (var index = 0; index < mesh.primitives.length; index++) {
  824. if (mesh.primitives[index].mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  825. //continue;
  826. }
  827. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], babylonMesh, babylonMesh, true);
  828. }
  829. // Finish
  830. return babylonMesh;
  831. };
  832. /**
  833. * Configures node transformation
  834. */
  835. var configureNode = function (babylonNode, node) {
  836. var position = BABYLON.Vector3.Zero();
  837. var rotation = BABYLON.Quaternion.Identity();
  838. var scaling = new BABYLON.Vector3(1, 1, 1);
  839. if (node.matrix) {
  840. var mat = BABYLON.Matrix.FromArray(node.matrix);
  841. mat.decompose(scaling, rotation, position);
  842. }
  843. else {
  844. if (node.translation) {
  845. position = BABYLON.Vector3.FromArray(node.translation);
  846. }
  847. if (node.rotation) {
  848. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  849. }
  850. if (node.scale) {
  851. scaling = BABYLON.Vector3.FromArray(node.scale);
  852. }
  853. }
  854. babylonNode.position = position;
  855. babylonNode.rotationQuaternion = rotation;
  856. if (babylonNode instanceof BABYLON.Mesh) {
  857. var mesh = babylonNode;
  858. mesh.scaling = scaling;
  859. }
  860. };
  861. /**
  862. * Imports a node
  863. */
  864. var importNode = function (runtime, node) {
  865. var babylonNode = null;
  866. if (runtime.importOnlyMeshes && (node.skin !== undefined || node.mesh !== undefined)) {
  867. if (runtime.importMeshesNames.length > 0 && runtime.importMeshesNames.indexOf(node.name) === -1) {
  868. return null;
  869. }
  870. }
  871. // Meshes
  872. if (node.skin !== undefined) {
  873. if (node.mesh !== undefined) {
  874. var skin = runtime.gltf.skins[node.skin];
  875. var newMesh = importMesh(runtime, node, runtime.gltf.meshes[node.mesh]);
  876. var newSkeleton = importSkeleton(runtime, node, skin);
  877. if (newSkeleton) {
  878. newMesh.skeleton = newSkeleton;
  879. skin.babylonSkeleton = newSkeleton;
  880. }
  881. babylonNode = newMesh;
  882. }
  883. }
  884. else if (node.mesh !== undefined) {
  885. babylonNode = importMesh(runtime, node, runtime.gltf.meshes[node.mesh]);
  886. }
  887. else if (node.camera !== undefined && !node.babylonNode && !runtime.importOnlyMeshes) {
  888. var camera = runtime.gltf.cameras[node.camera];
  889. if (camera !== undefined) {
  890. if (camera.type === "orthographic") {
  891. var orthographicCamera = camera.orthographic;
  892. var orthoCamera = new BABYLON.FreeCamera(node.name || "camera" + node.camera, BABYLON.Vector3.Zero(), runtime.babylonScene);
  893. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  894. orthoCamera.attachControl(runtime.babylonScene.getEngine().getRenderingCanvas());
  895. babylonNode = orthoCamera;
  896. }
  897. else if (camera.type === "perspective") {
  898. var perspectiveCamera = camera.perspective;
  899. var persCamera = new BABYLON.FreeCamera(node.name || "camera" + node.camera, BABYLON.Vector3.Zero(), runtime.babylonScene);
  900. persCamera.attachControl(runtime.babylonScene.getEngine().getRenderingCanvas());
  901. if (!perspectiveCamera.aspectRatio) {
  902. perspectiveCamera.aspectRatio = runtime.babylonScene.getEngine().getRenderWidth() / runtime.babylonScene.getEngine().getRenderHeight();
  903. }
  904. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  905. persCamera.maxZ = perspectiveCamera.zfar;
  906. persCamera.minZ = perspectiveCamera.znear;
  907. }
  908. babylonNode = persCamera;
  909. }
  910. }
  911. }
  912. // Empty node
  913. if (node.babylonNode) {
  914. return node.babylonNode;
  915. }
  916. else if (babylonNode === null) {
  917. var dummy = new BABYLON.Mesh(node.name || "mesh" + node.mesh, runtime.babylonScene);
  918. node.babylonNode = dummy;
  919. babylonNode = dummy;
  920. }
  921. if (babylonNode !== null) {
  922. configureNode(babylonNode, node);
  923. babylonNode.updateCache(true);
  924. node.babylonNode = babylonNode;
  925. }
  926. return babylonNode;
  927. };
  928. /**
  929. * Traverses nodes and creates them
  930. */
  931. var traverseNodes = function (runtime, index, parent, meshIncluded) {
  932. var node = runtime.gltf.nodes[index];
  933. var newNode = null;
  934. if (runtime.importOnlyMeshes && !meshIncluded) {
  935. if (runtime.importMeshesNames.indexOf(node.name) !== -1 || runtime.importMeshesNames.length === 0) {
  936. meshIncluded = true;
  937. }
  938. else {
  939. meshIncluded = false;
  940. }
  941. }
  942. else {
  943. meshIncluded = true;
  944. }
  945. if (meshIncluded) {
  946. newNode = importNode(runtime, node);
  947. if (newNode !== null) {
  948. newNode.id = createStringId(index);
  949. newNode.parent = parent;
  950. }
  951. }
  952. if (node.children) {
  953. for (var i = 0; i < node.children.length; i++) {
  954. traverseNodes(runtime, node.children[i], newNode, meshIncluded);
  955. }
  956. }
  957. };
  958. var importScene = function (runtime) {
  959. var scene = runtime.gltf.scene || 0;
  960. var scenes = runtime.gltf.scenes;
  961. if (scenes) {
  962. var nodes = scenes[scene].nodes;
  963. for (var i = 0; i < nodes.length; i++) {
  964. traverseNodes(runtime, nodes[i], null);
  965. }
  966. }
  967. else {
  968. for (var i = 0; i < runtime.gltf.nodes.length; i++) {
  969. traverseNodes(runtime, i, null);
  970. }
  971. }
  972. };
  973. /**
  974. * do stuff after buffers are loaded (e.g. hook up materials, load animations, etc.)
  975. */
  976. var postLoad = function (runtime) {
  977. importScene(runtime);
  978. // Set animations
  979. loadAnimations(runtime);
  980. for (var i = 0; i < runtime.babylonScene.skeletons.length; i++) {
  981. var skeleton = runtime.babylonScene.skeletons[i];
  982. runtime.babylonScene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  983. }
  984. // Revoke object urls created during load
  985. for (var i = 0; i < runtime.gltf.textures.length; i++) {
  986. var texture = runtime.gltf.textures[i];
  987. if (texture.blobURL) {
  988. URL.revokeObjectURL(texture.blobURL);
  989. }
  990. }
  991. };
  992. var BinaryReader = (function () {
  993. function BinaryReader(arrayBuffer) {
  994. this._arrayBuffer = arrayBuffer;
  995. this._dataView = new DataView(arrayBuffer);
  996. this._byteOffset = 0;
  997. }
  998. BinaryReader.prototype.getPosition = function () {
  999. return this._byteOffset;
  1000. };
  1001. BinaryReader.prototype.getLength = function () {
  1002. return this._arrayBuffer.byteLength;
  1003. };
  1004. BinaryReader.prototype.readUint32 = function () {
  1005. var value = this._dataView.getUint32(this._byteOffset, true);
  1006. this._byteOffset += 4;
  1007. return value;
  1008. };
  1009. BinaryReader.prototype.readUint8Array = function (length) {
  1010. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  1011. this._byteOffset += length;
  1012. return value;
  1013. };
  1014. BinaryReader.prototype.skipBytes = function (length) {
  1015. this._byteOffset += length;
  1016. };
  1017. return BinaryReader;
  1018. }());
  1019. /**
  1020. * glTF File Loader Plugin
  1021. */
  1022. var GLTFLoader = (function () {
  1023. function GLTFLoader() {
  1024. }
  1025. GLTFLoader.RegisterExtension = function (extension) {
  1026. if (GLTFLoader.Extensions[extension.name]) {
  1027. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1028. return;
  1029. }
  1030. GLTFLoader.Extensions[extension.name] = extension;
  1031. };
  1032. GLTFLoader.LoadMaterial = function (runtime, index) {
  1033. var material = runtime.gltf.materials[index];
  1034. if (!material)
  1035. return null;
  1036. material.babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + index, runtime.babylonScene);
  1037. material.babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1038. material.babylonMaterial.useScalarInLinearSpace = true;
  1039. return material;
  1040. };
  1041. GLTFLoader.LoadMetallicRoughnessMaterialPropertiesAsync = function (runtime, material, onSuccess, onError) {
  1042. // Ensure metallic workflow
  1043. material.babylonMaterial.metallic = 1;
  1044. material.babylonMaterial.roughness = 1;
  1045. var properties = material.pbrMetallicRoughness;
  1046. if (!properties) {
  1047. onSuccess();
  1048. return;
  1049. }
  1050. //
  1051. // Load Factors
  1052. //
  1053. material.babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  1054. material.babylonMaterial.metallic = properties.metallicFactor || 1;
  1055. material.babylonMaterial.roughness = properties.roughnessFactor || 1;
  1056. //
  1057. // Load Textures
  1058. //
  1059. if (!properties.baseColorTexture && !properties.metallicRoughnessTexture) {
  1060. onSuccess();
  1061. return;
  1062. }
  1063. var checkSuccess = function () {
  1064. if ((!properties.baseColorTexture || material.babylonMaterial.albedoTexture) &&
  1065. (!properties.metallicRoughnessTexture || material.babylonMaterial.metallicTexture)) {
  1066. onSuccess();
  1067. }
  1068. };
  1069. if (properties.baseColorTexture) {
  1070. GLTFLoader.LoadTextureAsync(runtime, properties.baseColorTexture, function (texture) {
  1071. material.babylonMaterial.albedoTexture = texture;
  1072. GLTFLoader.LoadAlphaProperties(runtime, material);
  1073. checkSuccess();
  1074. }, function () {
  1075. BABYLON.Tools.Error("Failed to load base color texture");
  1076. onError();
  1077. });
  1078. }
  1079. if (properties.metallicRoughnessTexture) {
  1080. GLTFLoader.LoadTextureAsync(runtime, properties.metallicRoughnessTexture, function (texture) {
  1081. material.babylonMaterial.metallicTexture = texture;
  1082. material.babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1083. material.babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1084. material.babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1085. checkSuccess();
  1086. }, function () {
  1087. BABYLON.Tools.Error("Failed to load metallic roughness texture");
  1088. onError();
  1089. });
  1090. }
  1091. };
  1092. GLTFLoader.LoadCommonMaterialPropertiesAsync = function (runtime, material, onSuccess, onError) {
  1093. //
  1094. // Load Factors
  1095. //
  1096. material.babylonMaterial.useEmissiveAsIllumination = (material.emissiveFactor || material.emissiveTexture) ? true : false;
  1097. material.babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  1098. if (material.doubleSided) {
  1099. material.babylonMaterial.backFaceCulling = false;
  1100. material.babylonMaterial.twoSidedLighting = true;
  1101. }
  1102. //
  1103. // Load Textures
  1104. //
  1105. if (!material.normalTexture && !material.occlusionTexture && !material.emissiveTexture) {
  1106. onSuccess();
  1107. return;
  1108. }
  1109. var checkSuccess = function () {
  1110. if ((!material.normalTexture || material.babylonMaterial.bumpTexture) &&
  1111. (!material.occlusionTexture || material.babylonMaterial.ambientTexture) &&
  1112. (!material.emissiveTexture || material.babylonMaterial.emissiveTexture)) {
  1113. onSuccess();
  1114. }
  1115. };
  1116. if (material.normalTexture) {
  1117. GLTFLoader.LoadTextureAsync(runtime, material.normalTexture, function (babylonTexture) {
  1118. material.babylonMaterial.bumpTexture = babylonTexture;
  1119. if (material.normalTexture.scale !== undefined) {
  1120. material.babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1121. }
  1122. checkSuccess();
  1123. }, function () {
  1124. BABYLON.Tools.Error("Failed to load normal texture");
  1125. onError();
  1126. });
  1127. }
  1128. if (material.occlusionTexture) {
  1129. GLTFLoader.LoadTextureAsync(runtime, material.occlusionTexture, function (babylonTexture) {
  1130. material.babylonMaterial.ambientTexture = babylonTexture;
  1131. material.babylonMaterial.useAmbientInGrayScale = true;
  1132. if (material.occlusionTexture.strength !== undefined) {
  1133. material.babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1134. }
  1135. checkSuccess();
  1136. }, function () {
  1137. BABYLON.Tools.Error("Failed to load occlusion texture");
  1138. onError();
  1139. });
  1140. }
  1141. if (material.emissiveTexture) {
  1142. GLTFLoader.LoadTextureAsync(runtime, material.emissiveTexture, function (babylonTexture) {
  1143. material.babylonMaterial.emissiveTexture = babylonTexture;
  1144. checkSuccess();
  1145. }, function () {
  1146. BABYLON.Tools.Error("Failed to load emissive texture");
  1147. onError();
  1148. });
  1149. }
  1150. };
  1151. GLTFLoader.LoadAlphaProperties = function (runtime, material) {
  1152. var alphaMode = material.alphaMode || "OPAQUE";
  1153. switch (alphaMode) {
  1154. case "OPAQUE":
  1155. // default is opaque
  1156. break;
  1157. case "MASK":
  1158. material.babylonMaterial.albedoTexture.hasAlpha = true;
  1159. material.babylonMaterial.useAlphaFromAlbedoTexture = false;
  1160. material.babylonMaterial.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  1161. break;
  1162. case "BLEND":
  1163. material.babylonMaterial.albedoTexture.hasAlpha = true;
  1164. material.babylonMaterial.useAlphaFromAlbedoTexture = true;
  1165. material.babylonMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1166. break;
  1167. default:
  1168. BABYLON.Tools.Error("Invalid alpha mode '" + material.alphaMode + "'");
  1169. }
  1170. };
  1171. GLTFLoader.LoadTextureAsync = function (runtime, textureInfo, onSuccess, onError) {
  1172. var texture = runtime.gltf.textures[textureInfo.index];
  1173. var texCoord = textureInfo.texCoord || 0;
  1174. if (!texture || texture.source === undefined) {
  1175. onError();
  1176. return;
  1177. }
  1178. if (texture.babylonTextures) {
  1179. var babylonTexture = texture.babylonTextures[texCoord];
  1180. if (!babylonTexture) {
  1181. for (var i = 0; i < texture.babylonTextures.length; i++) {
  1182. babylonTexture = texture.babylonTextures[i];
  1183. if (babylonTexture) {
  1184. babylonTexture = babylonTexture.clone();
  1185. babylonTexture.coordinatesIndex = texCoord;
  1186. break;
  1187. }
  1188. }
  1189. }
  1190. onSuccess(babylonTexture);
  1191. return;
  1192. }
  1193. var source = runtime.gltf.images[texture.source];
  1194. var sourceURL = runtime.rootUrl + source.uri;
  1195. if (texture.blobURL) {
  1196. sourceURL = texture.blobURL;
  1197. }
  1198. else {
  1199. if (source.uri === undefined) {
  1200. var bufferView = runtime.gltf.bufferViews[source.bufferView];
  1201. var buffer = GLTF2.GLTFUtils.GetBufferFromBufferView(runtime, bufferView, 0, bufferView.byteLength, GLTF2.EComponentType.UNSIGNED_BYTE);
  1202. texture.blobURL = URL.createObjectURL(new Blob([buffer], { type: source.mimeType }));
  1203. sourceURL = texture.blobURL;
  1204. }
  1205. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  1206. var decodedBuffer = new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri));
  1207. texture.blobURL = URL.createObjectURL(new Blob([decodedBuffer], { type: source.mimeType }));
  1208. sourceURL = texture.blobURL;
  1209. }
  1210. }
  1211. GLTFLoader._createTextureAsync(runtime, texture, texCoord, sourceURL, onSuccess, onError);
  1212. };
  1213. GLTFLoader._createTextureAsync = function (runtime, texture, texCoord, url, onSuccess, onError) {
  1214. var sampler = texture.sampler ? runtime.gltf.samplers[texture.sampler] : {};
  1215. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  1216. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1217. var babylonTexture = new BABYLON.Texture(url, runtime.babylonScene, noMipMaps, true, samplingMode, function () {
  1218. onSuccess(babylonTexture);
  1219. }, onError);
  1220. babylonTexture.coordinatesIndex = texCoord;
  1221. babylonTexture.wrapU = GLTF2.GLTFUtils.GetWrapMode(sampler.wrapS);
  1222. babylonTexture.wrapV = GLTF2.GLTFUtils.GetWrapMode(sampler.wrapT);
  1223. babylonTexture.name = texture.name;
  1224. // Cache the texture
  1225. texture.babylonTextures = texture.babylonTextures || [];
  1226. texture.babylonTextures[texCoord] = babylonTexture;
  1227. };
  1228. /**
  1229. * Import meshes
  1230. */
  1231. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onError) {
  1232. scene.useRightHandedSystem = true;
  1233. var runtime = GLTFLoader._createRuntime(scene, data, rootUrl, true);
  1234. if (!runtime) {
  1235. onError();
  1236. return;
  1237. }
  1238. if (meshesNames === "") {
  1239. runtime.importMeshesNames = [];
  1240. }
  1241. else if (typeof meshesNames === "string") {
  1242. runtime.importMeshesNames = [meshesNames];
  1243. }
  1244. else if (meshesNames && !(meshesNames instanceof Array)) {
  1245. runtime.importMeshesNames = [meshesNames];
  1246. }
  1247. else {
  1248. runtime.importMeshesNames = [];
  1249. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1250. }
  1251. // Load scene
  1252. importScene(runtime);
  1253. var meshes = [];
  1254. var skeletons = [];
  1255. // Fill arrays of meshes and skeletons
  1256. for (var i = 0; i < runtime.gltf.nodes.length; i++) {
  1257. var node = runtime.gltf.nodes[i];
  1258. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1259. meshes.push(node.babylonNode);
  1260. }
  1261. }
  1262. for (var i = 0; i < runtime.gltf.skins.length; i++) {
  1263. var skin = runtime.gltf.skins[i];
  1264. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1265. skeletons.push(skin.babylonSkeleton);
  1266. }
  1267. }
  1268. // Load buffers, materials, etc.
  1269. GLTFLoader._loadBuffersAsync(runtime, function () {
  1270. GLTFLoader._loadMaterialsAsync(runtime, function () {
  1271. postLoad(runtime);
  1272. onSuccess(meshes, null, skeletons);
  1273. }, onError);
  1274. }, onError);
  1275. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1276. onSuccess(meshes, null, skeletons);
  1277. }
  1278. };
  1279. /**
  1280. * Load scene
  1281. */
  1282. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1283. scene.useRightHandedSystem = true;
  1284. var runtime = GLTFLoader._createRuntime(scene, data, rootUrl, false);
  1285. if (!runtime) {
  1286. onError();
  1287. return;
  1288. }
  1289. importScene(runtime);
  1290. GLTFLoader._loadBuffersAsync(runtime, function () {
  1291. GLTFLoader._loadMaterialsAsync(runtime, function () {
  1292. postLoad(runtime);
  1293. onSuccess();
  1294. }, onError);
  1295. }, onError);
  1296. };
  1297. GLTFLoader._loadBuffersAsync = function (runtime, onSuccess, onError) {
  1298. var _this = this;
  1299. if (runtime.gltf.buffers.length == 0) {
  1300. onSuccess();
  1301. return;
  1302. }
  1303. var successCount = 0;
  1304. runtime.gltf.buffers.forEach(function (buffer, index) {
  1305. _this._loadBufferAsync(runtime, index, function () {
  1306. if (++successCount === runtime.gltf.buffers.length) {
  1307. onSuccess();
  1308. }
  1309. }, onError);
  1310. });
  1311. };
  1312. GLTFLoader._loadBufferAsync = function (runtime, index, onSuccess, onError) {
  1313. var buffer = runtime.gltf.buffers[index];
  1314. if (buffer.uri === undefined) {
  1315. // buffer.loadedBufferView should already be set
  1316. onSuccess();
  1317. }
  1318. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  1319. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  1320. setTimeout(function () {
  1321. buffer.loadedBufferView = new Uint8Array(data);
  1322. onSuccess();
  1323. });
  1324. }
  1325. else {
  1326. BABYLON.Tools.LoadFile(runtime.rootUrl + buffer.uri, function (data) {
  1327. buffer.loadedBufferView = new Uint8Array(data);
  1328. onSuccess();
  1329. }, null, null, true, onError);
  1330. }
  1331. };
  1332. GLTFLoader._loadMaterialsAsync = function (runtime, onSuccess, onError) {
  1333. var materials = runtime.gltf.materials;
  1334. if (!materials) {
  1335. onSuccess();
  1336. return;
  1337. }
  1338. var successCount = 0;
  1339. for (var i = 0; i < materials.length; i++) {
  1340. GLTF2.GLTFLoaderExtension.LoadMaterialAsync(runtime, i, function () {
  1341. if (++successCount === materials.length) {
  1342. onSuccess();
  1343. }
  1344. }, onError);
  1345. }
  1346. };
  1347. GLTFLoader._createRuntime = function (scene, data, rootUrl, importOnlyMeshes) {
  1348. var runtime = {
  1349. gltf: data.json,
  1350. babylonScene: scene,
  1351. rootUrl: rootUrl,
  1352. importOnlyMeshes: importOnlyMeshes,
  1353. };
  1354. var binaryBuffer;
  1355. var buffers = runtime.gltf.buffers;
  1356. if (buffers.length > 0 && buffers[0].uri === undefined) {
  1357. binaryBuffer = buffers[0];
  1358. }
  1359. if (data.bin) {
  1360. if (!binaryBuffer) {
  1361. BABYLON.Tools.Error("Unexpected BIN chunk");
  1362. return null;
  1363. }
  1364. if (binaryBuffer.byteLength != data.bin.byteLength) {
  1365. BABYLON.Tools.Error("Binary buffer length from JSON does not match chunk length");
  1366. return null;
  1367. }
  1368. binaryBuffer.loadedBufferView = data.bin;
  1369. }
  1370. GLTF2.GLTFLoaderExtension.PostCreateRuntime(runtime);
  1371. return runtime;
  1372. };
  1373. return GLTFLoader;
  1374. }());
  1375. GLTFLoader.Extensions = {};
  1376. GLTF2.GLTFLoader = GLTFLoader;
  1377. BABYLON.GLTFFileLoader.GLTFLoaderV2 = new GLTFLoader();
  1378. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1379. })(BABYLON || (BABYLON = {}));
  1380. //# sourceMappingURL=babylon.glTFLoader.js.map
  1381. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1382. var BABYLON;
  1383. (function (BABYLON) {
  1384. var GLTF2;
  1385. (function (GLTF2) {
  1386. /**
  1387. * Utils functions for GLTF
  1388. */
  1389. var GLTFUtils = (function () {
  1390. function GLTFUtils() {
  1391. }
  1392. /**
  1393. * If the uri is a base64 string
  1394. * @param uri: the uri to test
  1395. */
  1396. GLTFUtils.IsBase64 = function (uri) {
  1397. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1398. };
  1399. /**
  1400. * Decode the base64 uri
  1401. * @param uri: the uri to decode
  1402. */
  1403. GLTFUtils.DecodeBase64 = function (uri) {
  1404. var decodedString = atob(uri.split(",")[1]);
  1405. var bufferLength = decodedString.length;
  1406. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1407. for (var i = 0; i < bufferLength; i++) {
  1408. bufferView[i] = decodedString.charCodeAt(i);
  1409. }
  1410. return bufferView.buffer;
  1411. };
  1412. /**
  1413. * Returns the wrap mode of the texture
  1414. * @param mode: the mode value
  1415. */
  1416. GLTFUtils.GetWrapMode = function (mode) {
  1417. switch (mode) {
  1418. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1419. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1420. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1421. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1422. }
  1423. };
  1424. /**
  1425. * Returns the byte stride giving an accessor
  1426. * @param accessor: the GLTF accessor objet
  1427. */
  1428. GLTFUtils.GetByteStrideFromType = function (accessor) {
  1429. // Needs this function since "byteStride" isn't requiered in glTF format
  1430. var type = accessor.type;
  1431. switch (type) {
  1432. case "VEC2": return 2;
  1433. case "VEC3": return 3;
  1434. case "VEC4": return 4;
  1435. case "MAT2": return 4;
  1436. case "MAT3": return 9;
  1437. case "MAT4": return 16;
  1438. default: return 1;
  1439. }
  1440. };
  1441. /**
  1442. * Returns the texture filter mode giving a mode value
  1443. * @param mode: the filter mode value
  1444. */
  1445. GLTFUtils.GetTextureFilterMode = function (mode) {
  1446. switch (mode) {
  1447. case GLTF2.ETextureMinFilter.LINEAR:
  1448. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST:
  1449. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1450. case GLTF2.ETextureMinFilter.NEAREST:
  1451. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1452. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1453. }
  1454. };
  1455. GLTFUtils.GetBufferFromBufferView = function (runtime, bufferView, byteOffset, byteLength, componentType) {
  1456. var byteOffset = bufferView.byteOffset + byteOffset;
  1457. var loadedBufferView = runtime.gltf.buffers[bufferView.buffer].loadedBufferView;
  1458. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  1459. throw new Error("Buffer access is out of range");
  1460. }
  1461. var buffer = loadedBufferView.buffer;
  1462. byteOffset += loadedBufferView.byteOffset;
  1463. switch (componentType) {
  1464. case GLTF2.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  1465. case GLTF2.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  1466. case GLTF2.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  1467. case GLTF2.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  1468. case GLTF2.EComponentType.UNSIGNED_INT: return new Uint32Array(buffer, byteOffset, byteLength);
  1469. default: return new Float32Array(buffer, byteOffset, byteLength);
  1470. }
  1471. };
  1472. /**
  1473. * Returns a buffer from its accessor
  1474. * @param runtime: the GLTF runtime
  1475. * @param accessor: the GLTF accessor
  1476. */
  1477. GLTFUtils.GetBufferFromAccessor = function (runtime, accessor) {
  1478. var bufferView = runtime.gltf.bufferViews[accessor.bufferView];
  1479. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  1480. return GLTFUtils.GetBufferFromBufferView(runtime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  1481. };
  1482. /**
  1483. * Decodes a buffer view into a string
  1484. * @param view: the buffer view
  1485. */
  1486. GLTFUtils.DecodeBufferToText = function (view) {
  1487. var result = "";
  1488. var length = view.byteLength;
  1489. for (var i = 0; i < length; ++i) {
  1490. result += String.fromCharCode(view[i]);
  1491. }
  1492. return result;
  1493. };
  1494. /**
  1495. * Returns the default material of gltf.
  1496. * @param scene: the Babylon.js scene
  1497. */
  1498. GLTFUtils.GetDefaultMaterial = function (runtime) {
  1499. if (!runtime.defaultMaterial) {
  1500. var material = new BABYLON.PBRMaterial("gltf_default", runtime.babylonScene);
  1501. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1502. material.metallic = 1;
  1503. material.roughness = 1;
  1504. runtime.defaultMaterial = material;
  1505. }
  1506. return runtime.defaultMaterial;
  1507. };
  1508. return GLTFUtils;
  1509. }());
  1510. GLTF2.GLTFUtils = GLTFUtils;
  1511. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1512. })(BABYLON || (BABYLON = {}));
  1513. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  1514. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1515. var BABYLON;
  1516. (function (BABYLON) {
  1517. var GLTF2;
  1518. (function (GLTF2) {
  1519. var GLTFLoaderExtension = (function () {
  1520. function GLTFLoaderExtension(name) {
  1521. this._name = name;
  1522. }
  1523. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  1524. get: function () {
  1525. return this._name;
  1526. },
  1527. enumerable: true,
  1528. configurable: true
  1529. });
  1530. GLTFLoaderExtension.prototype.postCreateRuntime = function (runtime) { };
  1531. // Return true to stop other extensions from loading materials.
  1532. GLTFLoaderExtension.prototype.loadMaterialAsync = function (runtime, index, onSuccess, onError) { return false; };
  1533. // ---------
  1534. // Utilities
  1535. // ---------
  1536. GLTFLoaderExtension.PostCreateRuntime = function (runtime) {
  1537. for (var extensionName in GLTF2.GLTFLoader.Extensions) {
  1538. var extension = GLTF2.GLTFLoader.Extensions[extensionName];
  1539. extension.postCreateRuntime(runtime);
  1540. }
  1541. };
  1542. GLTFLoaderExtension.LoadMaterialAsync = function (runtime, index, onSuccess, onError) {
  1543. for (var extensionName in GLTF2.GLTFLoader.Extensions) {
  1544. var extension = GLTF2.GLTFLoader.Extensions[extensionName];
  1545. if (extension.loadMaterialAsync(runtime, index, onSuccess, onError)) {
  1546. return;
  1547. }
  1548. }
  1549. var material = GLTF2.GLTFLoader.LoadMaterial(runtime, index);
  1550. if (!material) {
  1551. onSuccess();
  1552. return;
  1553. }
  1554. var metallicRoughnessPropertiesSuccess = false;
  1555. var commonPropertiesSuccess = false;
  1556. var checkSuccess = function () {
  1557. if (metallicRoughnessPropertiesSuccess && commonPropertiesSuccess) {
  1558. onSuccess();
  1559. }
  1560. };
  1561. GLTF2.GLTFLoader.LoadMetallicRoughnessMaterialPropertiesAsync(runtime, material, function () {
  1562. metallicRoughnessPropertiesSuccess = true;
  1563. checkSuccess();
  1564. }, onError);
  1565. GLTF2.GLTFLoader.LoadCommonMaterialPropertiesAsync(runtime, material, function () {
  1566. commonPropertiesSuccess = true;
  1567. checkSuccess();
  1568. }, onError);
  1569. };
  1570. return GLTFLoaderExtension;
  1571. }());
  1572. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  1573. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1574. })(BABYLON || (BABYLON = {}));
  1575. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  1576. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1577. var __extends = (this && this.__extends) || (function () {
  1578. var extendStatics = Object.setPrototypeOf ||
  1579. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1580. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1581. return function (d, b) {
  1582. extendStatics(d, b);
  1583. function __() { this.constructor = d; }
  1584. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1585. };
  1586. })();
  1587. var BABYLON;
  1588. (function (BABYLON) {
  1589. var GLTF2;
  1590. (function (GLTF2) {
  1591. var GLTFMaterialsPbrSpecularGlossinessExtension = (function (_super) {
  1592. __extends(GLTFMaterialsPbrSpecularGlossinessExtension, _super);
  1593. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  1594. return _super.call(this, "KHR_materials_pbrSpecularGlossiness") || this;
  1595. }
  1596. GLTFMaterialsPbrSpecularGlossinessExtension.prototype.loadMaterialAsync = function (runtime, index, onSuccess, onError) {
  1597. var material = GLTF2.GLTFLoader.LoadMaterial(runtime, index);
  1598. if (!material || !material.extensions)
  1599. return false;
  1600. var properties = material.extensions[this.name];
  1601. if (!properties)
  1602. return false;
  1603. //
  1604. // Load Factors
  1605. //
  1606. material.babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  1607. material.babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  1608. material.babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  1609. //
  1610. // Load Textures
  1611. //
  1612. var commonMaterialPropertiesSuccess = false;
  1613. var checkSuccess = function () {
  1614. if ((!properties.diffuseTexture || material.babylonMaterial.albedoTexture) &&
  1615. (!properties.specularGlossinessTexture || material.babylonMaterial.reflectivityTexture) &&
  1616. commonMaterialPropertiesSuccess) {
  1617. onSuccess();
  1618. }
  1619. };
  1620. if (properties.diffuseTexture) {
  1621. GLTF2.GLTFLoader.LoadTextureAsync(runtime, properties.diffuseTexture, function (texture) {
  1622. material.babylonMaterial.albedoTexture = texture;
  1623. GLTF2.GLTFLoader.LoadAlphaProperties(runtime, material);
  1624. checkSuccess();
  1625. }, function () {
  1626. BABYLON.Tools.Warn("Failed to load diffuse texture");
  1627. onError();
  1628. });
  1629. }
  1630. if (properties.specularGlossinessTexture) {
  1631. GLTF2.GLTFLoader.LoadTextureAsync(runtime, properties.specularGlossinessTexture, function (texture) {
  1632. material.babylonMaterial.reflectivityTexture = texture;
  1633. material.babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  1634. checkSuccess();
  1635. }, function () {
  1636. BABYLON.Tools.Warn("Failed to load metallic roughness texture");
  1637. onError();
  1638. });
  1639. }
  1640. GLTF2.GLTFLoader.LoadCommonMaterialPropertiesAsync(runtime, material, function () {
  1641. commonMaterialPropertiesSuccess = true;
  1642. checkSuccess();
  1643. }, onError);
  1644. return true;
  1645. };
  1646. return GLTFMaterialsPbrSpecularGlossinessExtension;
  1647. }(GLTF2.GLTFLoaderExtension));
  1648. GLTF2.GLTFMaterialsPbrSpecularGlossinessExtension = GLTFMaterialsPbrSpecularGlossinessExtension;
  1649. GLTF2.GLTFLoader.RegisterExtension(new GLTFMaterialsPbrSpecularGlossinessExtension());
  1650. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1651. })(BABYLON || (BABYLON = {}));
  1652. //# sourceMappingURL=babylon.glTFMaterialsPbrSpecularGlossinessExtension.js.map