babylon.glTF1FileLoader.js 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. var GLTFLoaderCoordinateSystemMode;
  5. (function (GLTFLoaderCoordinateSystemMode) {
  6. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  7. // NOTE: When scene.useRightHandedSystem is false, an additional transform will be added to the root to transform the data from right-handed to left-handed.
  8. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  9. // The glTF right-handed data is not transformed in any form and is loaded directly.
  10. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  11. // Sets the useRightHandedSystem flag on the scene.
  12. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  13. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  14. var GLTFFileLoader = /** @class */ (function () {
  15. function GLTFFileLoader() {
  16. // V2 options
  17. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  18. this.name = "gltf";
  19. this.extensions = {
  20. ".gltf": { isBinary: false },
  21. ".glb": { isBinary: true }
  22. };
  23. }
  24. GLTFFileLoader.prototype.dispose = function () {
  25. if (this._loader) {
  26. this._loader.dispose();
  27. this._loader = null;
  28. }
  29. };
  30. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  31. var loaderData = GLTFFileLoader._parse(data, onError);
  32. if (!loaderData) {
  33. return;
  34. }
  35. if (this.onParsed) {
  36. this.onParsed(loaderData);
  37. }
  38. this._loader = this._getLoader(loaderData, onError);
  39. if (!this._loader) {
  40. return;
  41. }
  42. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  43. };
  44. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  45. var loaderData = GLTFFileLoader._parse(data, onError);
  46. if (!loaderData) {
  47. return;
  48. }
  49. if (this.onParsed) {
  50. this.onParsed(loaderData);
  51. }
  52. this._loader = this._getLoader(loaderData, onError);
  53. if (!this._loader) {
  54. return;
  55. }
  56. return this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  57. };
  58. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  59. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  60. };
  61. GLTFFileLoader._parse = function (data, onError) {
  62. try {
  63. if (data instanceof ArrayBuffer) {
  64. return GLTFFileLoader._parseBinary(data, onError);
  65. }
  66. return {
  67. json: JSON.parse(data),
  68. bin: null
  69. };
  70. }
  71. catch (e) {
  72. onError(e.message);
  73. return null;
  74. }
  75. };
  76. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  77. var loaderVersion = { major: 2, minor: 0 };
  78. var asset = loaderData.json.asset || {};
  79. var version = GLTFFileLoader._parseVersion(asset.version);
  80. if (!version) {
  81. onError("Invalid version: " + asset.version);
  82. return null;
  83. }
  84. if (asset.minVersion !== undefined) {
  85. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  86. if (!minVersion) {
  87. onError("Invalid minimum version: " + asset.minVersion);
  88. return null;
  89. }
  90. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  91. onError("Incompatible minimum version: " + asset.minVersion);
  92. return null;
  93. }
  94. }
  95. var createLoaders = {
  96. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  97. 2: GLTFFileLoader.CreateGLTFLoaderV2
  98. };
  99. var createLoader = createLoaders[version.major];
  100. if (!createLoader) {
  101. onError("Unsupported version: " + asset.version);
  102. return null;
  103. }
  104. return createLoader(this);
  105. };
  106. GLTFFileLoader._parseBinary = function (data, onError) {
  107. var Binary = {
  108. Magic: 0x46546C67
  109. };
  110. var binaryReader = new BinaryReader(data);
  111. var magic = binaryReader.readUint32();
  112. if (magic !== Binary.Magic) {
  113. onError("Unexpected magic: " + magic);
  114. return null;
  115. }
  116. var version = binaryReader.readUint32();
  117. switch (version) {
  118. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  119. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  120. }
  121. onError("Unsupported version: " + version);
  122. return null;
  123. };
  124. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  125. var ContentFormat = {
  126. JSON: 0
  127. };
  128. var length = binaryReader.readUint32();
  129. if (length != binaryReader.getLength()) {
  130. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  131. return null;
  132. }
  133. var contentLength = binaryReader.readUint32();
  134. var contentFormat = binaryReader.readUint32();
  135. var content;
  136. switch (contentFormat) {
  137. case ContentFormat.JSON:
  138. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  139. break;
  140. default:
  141. onError("Unexpected content format: " + contentFormat);
  142. return null;
  143. }
  144. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  145. var body = binaryReader.readUint8Array(bytesRemaining);
  146. return {
  147. json: content,
  148. bin: body
  149. };
  150. };
  151. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  152. var ChunkFormat = {
  153. JSON: 0x4E4F534A,
  154. BIN: 0x004E4942
  155. };
  156. var length = binaryReader.readUint32();
  157. if (length !== binaryReader.getLength()) {
  158. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  159. return null;
  160. }
  161. // JSON chunk
  162. var chunkLength = binaryReader.readUint32();
  163. var chunkFormat = binaryReader.readUint32();
  164. if (chunkFormat !== ChunkFormat.JSON) {
  165. onError("First chunk format is not JSON");
  166. return null;
  167. }
  168. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  169. // Look for BIN chunk
  170. var bin = null;
  171. while (binaryReader.getPosition() < binaryReader.getLength()) {
  172. var chunkLength_1 = binaryReader.readUint32();
  173. var chunkFormat_1 = binaryReader.readUint32();
  174. switch (chunkFormat_1) {
  175. case ChunkFormat.JSON:
  176. onError("Unexpected JSON chunk");
  177. return null;
  178. case ChunkFormat.BIN:
  179. bin = binaryReader.readUint8Array(chunkLength_1);
  180. break;
  181. default:
  182. // ignore unrecognized chunkFormat
  183. binaryReader.skipBytes(chunkLength_1);
  184. break;
  185. }
  186. }
  187. return {
  188. json: json,
  189. bin: bin
  190. };
  191. };
  192. GLTFFileLoader._parseVersion = function (version) {
  193. var match = (version + "").match(/^(\d+)\.(\d+)$/);
  194. if (!match) {
  195. return null;
  196. }
  197. return {
  198. major: parseInt(match[1]),
  199. minor: parseInt(match[2])
  200. };
  201. };
  202. GLTFFileLoader._compareVersion = function (a, b) {
  203. if (a.major > b.major)
  204. return 1;
  205. if (a.major < b.major)
  206. return -1;
  207. if (a.minor > b.minor)
  208. return 1;
  209. if (a.minor < b.minor)
  210. return -1;
  211. return 0;
  212. };
  213. GLTFFileLoader._decodeBufferToText = function (buffer) {
  214. var result = "";
  215. var length = buffer.byteLength;
  216. for (var i = 0; i < length; i++) {
  217. result += String.fromCharCode(buffer[i]);
  218. }
  219. return result;
  220. };
  221. // V1 options
  222. GLTFFileLoader.HomogeneousCoordinates = false;
  223. GLTFFileLoader.IncrementalLoading = true;
  224. return GLTFFileLoader;
  225. }());
  226. BABYLON.GLTFFileLoader = GLTFFileLoader;
  227. var BinaryReader = /** @class */ (function () {
  228. function BinaryReader(arrayBuffer) {
  229. this._arrayBuffer = arrayBuffer;
  230. this._dataView = new DataView(arrayBuffer);
  231. this._byteOffset = 0;
  232. }
  233. BinaryReader.prototype.getPosition = function () {
  234. return this._byteOffset;
  235. };
  236. BinaryReader.prototype.getLength = function () {
  237. return this._arrayBuffer.byteLength;
  238. };
  239. BinaryReader.prototype.readUint32 = function () {
  240. var value = this._dataView.getUint32(this._byteOffset, true);
  241. this._byteOffset += 4;
  242. return value;
  243. };
  244. BinaryReader.prototype.readUint8Array = function (length) {
  245. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  246. this._byteOffset += length;
  247. return value;
  248. };
  249. BinaryReader.prototype.skipBytes = function (length) {
  250. this._byteOffset += length;
  251. };
  252. return BinaryReader;
  253. }());
  254. if (BABYLON.SceneLoader) {
  255. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  256. }
  257. })(BABYLON || (BABYLON = {}));
  258. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  259. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  260. var BABYLON;
  261. (function (BABYLON) {
  262. var GLTF1;
  263. (function (GLTF1) {
  264. /**
  265. * Enums
  266. */
  267. var EComponentType;
  268. (function (EComponentType) {
  269. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  270. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  271. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  272. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  273. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  274. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  275. var EShaderType;
  276. (function (EShaderType) {
  277. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  278. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  279. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  280. var EParameterType;
  281. (function (EParameterType) {
  282. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  283. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  284. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  285. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  286. EParameterType[EParameterType["INT"] = 5124] = "INT";
  287. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  288. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  289. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  290. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  291. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  292. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  293. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  294. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  295. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  296. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  297. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  298. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  299. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  300. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  301. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  302. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  303. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  304. var ETextureWrapMode;
  305. (function (ETextureWrapMode) {
  306. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  307. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  308. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  309. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  310. var ETextureFilterType;
  311. (function (ETextureFilterType) {
  312. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  313. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  314. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  315. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  316. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  317. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  318. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  319. var ETextureFormat;
  320. (function (ETextureFormat) {
  321. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  322. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  323. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  324. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  325. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  326. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  327. var ECullingType;
  328. (function (ECullingType) {
  329. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  330. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  331. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  332. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  333. var EBlendingFunction;
  334. (function (EBlendingFunction) {
  335. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  336. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  337. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  338. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  339. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  340. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  341. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  342. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  343. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  344. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  345. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  346. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  347. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  348. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  349. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  350. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  351. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  352. })(BABYLON || (BABYLON = {}));
  353. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  354. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  355. var BABYLON;
  356. (function (BABYLON) {
  357. var GLTF1;
  358. (function (GLTF1) {
  359. /**
  360. * Tokenizer. Used for shaders compatibility
  361. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  362. */
  363. var ETokenType;
  364. (function (ETokenType) {
  365. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  366. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  367. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  368. })(ETokenType || (ETokenType = {}));
  369. var Tokenizer = /** @class */ (function () {
  370. function Tokenizer(toParse) {
  371. this._pos = 0;
  372. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  373. this._toParse = toParse;
  374. this._maxPos = toParse.length;
  375. }
  376. Tokenizer.prototype.getNextToken = function () {
  377. if (this.isEnd())
  378. return ETokenType.END_OF_INPUT;
  379. this.currentString = this.read();
  380. this.currentToken = ETokenType.UNKNOWN;
  381. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  382. this.currentToken = ETokenType.IDENTIFIER;
  383. this.currentIdentifier = this.currentString;
  384. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  385. this.currentIdentifier += this.currentString;
  386. this.forward();
  387. }
  388. }
  389. return this.currentToken;
  390. };
  391. Tokenizer.prototype.peek = function () {
  392. return this._toParse[this._pos];
  393. };
  394. Tokenizer.prototype.read = function () {
  395. return this._toParse[this._pos++];
  396. };
  397. Tokenizer.prototype.forward = function () {
  398. this._pos++;
  399. };
  400. Tokenizer.prototype.isEnd = function () {
  401. return this._pos >= this._maxPos;
  402. };
  403. return Tokenizer;
  404. }());
  405. /**
  406. * Values
  407. */
  408. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  409. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  410. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  411. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  412. /**
  413. * Parse
  414. */
  415. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  416. for (var buf in parsedBuffers) {
  417. var parsedBuffer = parsedBuffers[buf];
  418. gltfRuntime.buffers[buf] = parsedBuffer;
  419. gltfRuntime.buffersCount++;
  420. }
  421. };
  422. var parseShaders = function (parsedShaders, gltfRuntime) {
  423. for (var sha in parsedShaders) {
  424. var parsedShader = parsedShaders[sha];
  425. gltfRuntime.shaders[sha] = parsedShader;
  426. gltfRuntime.shaderscount++;
  427. }
  428. };
  429. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  430. for (var object in parsedObjects) {
  431. var parsedObject = parsedObjects[object];
  432. gltfRuntime[runtimeProperty][object] = parsedObject;
  433. }
  434. };
  435. /**
  436. * Utils
  437. */
  438. var normalizeUVs = function (buffer) {
  439. if (!buffer) {
  440. return;
  441. }
  442. for (var i = 0; i < buffer.length / 2; i++) {
  443. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  444. }
  445. };
  446. var getAttribute = function (attributeParameter) {
  447. if (attributeParameter.semantic === "NORMAL") {
  448. return "normal";
  449. }
  450. else if (attributeParameter.semantic === "POSITION") {
  451. return "position";
  452. }
  453. else if (attributeParameter.semantic === "JOINT") {
  454. return "matricesIndices";
  455. }
  456. else if (attributeParameter.semantic === "WEIGHT") {
  457. return "matricesWeights";
  458. }
  459. else if (attributeParameter.semantic === "COLOR") {
  460. return "color";
  461. }
  462. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  463. var channel = Number(attributeParameter.semantic.split("_")[1]);
  464. return "uv" + (channel === 0 ? "" : channel + 1);
  465. }
  466. return null;
  467. };
  468. /**
  469. * Loads and creates animations
  470. */
  471. var loadAnimations = function (gltfRuntime) {
  472. for (var anim in gltfRuntime.animations) {
  473. var animation = gltfRuntime.animations[anim];
  474. var lastAnimation = null;
  475. for (var i = 0; i < animation.channels.length; i++) {
  476. // Get parameters and load buffers
  477. var channel = animation.channels[i];
  478. var sampler = animation.samplers[channel.sampler];
  479. if (!sampler) {
  480. continue;
  481. }
  482. var inputData = null;
  483. var outputData = null;
  484. if (animation.parameters) {
  485. inputData = animation.parameters[sampler.input];
  486. outputData = animation.parameters[sampler.output];
  487. }
  488. else {
  489. inputData = sampler.input;
  490. outputData = sampler.output;
  491. }
  492. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  493. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  494. var targetID = channel.target.id;
  495. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  496. if (targetNode === null) {
  497. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  498. }
  499. if (targetNode === null) {
  500. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  501. continue;
  502. }
  503. var isBone = targetNode instanceof BABYLON.Bone;
  504. // Get target path (position, rotation or scaling)
  505. var targetPath = channel.target.path;
  506. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  507. if (targetPathIndex !== -1) {
  508. targetPath = babylonAnimationPaths[targetPathIndex];
  509. }
  510. // Determine animation type
  511. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  512. if (!isBone) {
  513. if (targetPath === "rotationQuaternion") {
  514. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  515. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  516. }
  517. else {
  518. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  519. }
  520. }
  521. // Create animation and key frames
  522. var babylonAnimation = null;
  523. var keys = [];
  524. var arrayOffset = 0;
  525. var modifyKey = false;
  526. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  527. babylonAnimation = lastAnimation;
  528. modifyKey = true;
  529. }
  530. if (!modifyKey) {
  531. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  532. }
  533. // For each frame
  534. for (var j = 0; j < bufferInput.length; j++) {
  535. var value = null;
  536. if (targetPath === "rotationQuaternion") {
  537. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  538. arrayOffset += 4;
  539. }
  540. else {
  541. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  542. arrayOffset += 3;
  543. }
  544. if (isBone) {
  545. var bone = targetNode;
  546. var translation = BABYLON.Vector3.Zero();
  547. var rotationQuaternion = new BABYLON.Quaternion();
  548. var scaling = BABYLON.Vector3.Zero();
  549. // Warning on decompose
  550. var mat = bone.getBaseMatrix();
  551. if (modifyKey) {
  552. mat = lastAnimation.getKeys()[j].value;
  553. }
  554. mat.decompose(scaling, rotationQuaternion, translation);
  555. if (targetPath === "position") {
  556. translation = value;
  557. }
  558. else if (targetPath === "rotationQuaternion") {
  559. rotationQuaternion = value;
  560. }
  561. else {
  562. scaling = value;
  563. }
  564. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  565. }
  566. if (!modifyKey) {
  567. keys.push({
  568. frame: bufferInput[j],
  569. value: value
  570. });
  571. }
  572. else {
  573. lastAnimation.getKeys()[j].value = value;
  574. }
  575. }
  576. // Finish
  577. if (!modifyKey) {
  578. babylonAnimation.setKeys(keys);
  579. targetNode.animations.push(babylonAnimation);
  580. }
  581. lastAnimation = babylonAnimation;
  582. gltfRuntime.scene.stopAnimation(targetNode);
  583. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  584. }
  585. }
  586. };
  587. /**
  588. * Returns the bones transformation matrix
  589. */
  590. var configureBoneTransformation = function (node) {
  591. var mat = null;
  592. if (node.translation || node.rotation || node.scale) {
  593. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  594. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  595. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  596. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  597. }
  598. else {
  599. mat = BABYLON.Matrix.FromArray(node.matrix);
  600. }
  601. return mat;
  602. };
  603. /**
  604. * Returns the parent bone
  605. */
  606. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  607. // Try to find
  608. for (var i = 0; i < newSkeleton.bones.length; i++) {
  609. if (newSkeleton.bones[i].name === jointName) {
  610. return newSkeleton.bones[i];
  611. }
  612. }
  613. // Not found, search in gltf nodes
  614. var nodes = gltfRuntime.nodes;
  615. for (var nde in nodes) {
  616. var node = nodes[nde];
  617. if (!node.jointName) {
  618. continue;
  619. }
  620. var children = node.children;
  621. for (var i = 0; i < children.length; i++) {
  622. var child = gltfRuntime.nodes[children[i]];
  623. if (!child.jointName) {
  624. continue;
  625. }
  626. if (child.jointName === jointName) {
  627. var mat = configureBoneTransformation(node);
  628. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  629. bone.id = nde;
  630. return bone;
  631. }
  632. }
  633. }
  634. return null;
  635. };
  636. /**
  637. * Returns the appropriate root node
  638. */
  639. var getNodeToRoot = function (nodesToRoot, id) {
  640. for (var i = 0; i < nodesToRoot.length; i++) {
  641. var nodeToRoot = nodesToRoot[i];
  642. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  643. var child = nodeToRoot.node.children[j];
  644. if (child === id) {
  645. return nodeToRoot.bone;
  646. }
  647. }
  648. }
  649. return null;
  650. };
  651. /**
  652. * Returns the node with the joint name
  653. */
  654. var getJointNode = function (gltfRuntime, jointName) {
  655. var nodes = gltfRuntime.nodes;
  656. var node = nodes[jointName];
  657. if (node) {
  658. return {
  659. node: node,
  660. id: jointName
  661. };
  662. }
  663. for (var nde in nodes) {
  664. node = nodes[nde];
  665. if (node.jointName === jointName) {
  666. return {
  667. node: node,
  668. id: nde
  669. };
  670. }
  671. }
  672. return null;
  673. };
  674. /**
  675. * Checks if a nodes is in joints
  676. */
  677. var nodeIsInJoints = function (skins, id) {
  678. for (var i = 0; i < skins.jointNames.length; i++) {
  679. if (skins.jointNames[i] === id) {
  680. return true;
  681. }
  682. }
  683. return false;
  684. };
  685. /**
  686. * Fills the nodes to root for bones and builds hierarchy
  687. */
  688. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  689. // Creates nodes for root
  690. for (var nde in gltfRuntime.nodes) {
  691. var node = gltfRuntime.nodes[nde];
  692. var id = nde;
  693. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  694. continue;
  695. }
  696. // Create node to root bone
  697. var mat = configureBoneTransformation(node);
  698. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  699. bone.id = id;
  700. nodesToRoot.push({ bone: bone, node: node, id: id });
  701. }
  702. // Parenting
  703. for (var i = 0; i < nodesToRoot.length; i++) {
  704. var nodeToRoot = nodesToRoot[i];
  705. var children = nodeToRoot.node.children;
  706. for (var j = 0; j < children.length; j++) {
  707. var child = null;
  708. for (var k = 0; k < nodesToRoot.length; k++) {
  709. if (nodesToRoot[k].id === children[j]) {
  710. child = nodesToRoot[k];
  711. break;
  712. }
  713. }
  714. if (child) {
  715. child.bone._parent = nodeToRoot.bone;
  716. nodeToRoot.bone.children.push(child.bone);
  717. }
  718. }
  719. }
  720. };
  721. /**
  722. * Imports a skeleton
  723. */
  724. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  725. if (!newSkeleton) {
  726. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  727. }
  728. if (!skins.babylonSkeleton) {
  729. return newSkeleton;
  730. }
  731. // Find the root bones
  732. var nodesToRoot = [];
  733. var nodesToRootToAdd = [];
  734. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  735. newSkeleton.bones = [];
  736. // Joints
  737. for (var i = 0; i < skins.jointNames.length; i++) {
  738. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  739. var node = jointNode.node;
  740. if (!node) {
  741. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  742. continue;
  743. }
  744. var id = jointNode.id;
  745. // Optimize, if the bone already exists...
  746. var existingBone = gltfRuntime.scene.getBoneByID(id);
  747. if (existingBone) {
  748. newSkeleton.bones.push(existingBone);
  749. continue;
  750. }
  751. // Search for parent bone
  752. var foundBone = false;
  753. var parentBone = null;
  754. for (var j = 0; j < i; j++) {
  755. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  756. if (!joint) {
  757. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  758. continue;
  759. }
  760. var children = joint.children;
  761. if (!children) {
  762. continue;
  763. }
  764. foundBone = false;
  765. for (var k = 0; k < children.length; k++) {
  766. if (children[k] === id) {
  767. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  768. foundBone = true;
  769. break;
  770. }
  771. }
  772. if (foundBone) {
  773. break;
  774. }
  775. }
  776. // Create bone
  777. var mat = configureBoneTransformation(node);
  778. if (!parentBone && nodesToRoot.length > 0) {
  779. parentBone = getNodeToRoot(nodesToRoot, id);
  780. if (parentBone) {
  781. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  782. nodesToRootToAdd.push(parentBone);
  783. }
  784. }
  785. }
  786. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  787. bone.id = id;
  788. }
  789. // Polish
  790. var bones = newSkeleton.bones;
  791. newSkeleton.bones = [];
  792. for (var i = 0; i < skins.jointNames.length; i++) {
  793. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  794. if (!jointNode) {
  795. continue;
  796. }
  797. for (var j = 0; j < bones.length; j++) {
  798. if (bones[j].id === jointNode.id) {
  799. newSkeleton.bones.push(bones[j]);
  800. break;
  801. }
  802. }
  803. }
  804. newSkeleton.prepare();
  805. // Finish
  806. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  807. newSkeleton.bones.push(nodesToRootToAdd[i]);
  808. }
  809. return newSkeleton;
  810. };
  811. /**
  812. * Imports a mesh and its geometries
  813. */
  814. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  815. if (!newMesh) {
  816. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  817. newMesh.id = id;
  818. }
  819. if (!node.babylonNode) {
  820. return newMesh;
  821. }
  822. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  823. if (!newMesh.material) {
  824. newMesh.material = multiMat;
  825. }
  826. var vertexData = new BABYLON.VertexData();
  827. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  828. var verticesStarts = new Array();
  829. var verticesCounts = new Array();
  830. var indexStarts = new Array();
  831. var indexCounts = new Array();
  832. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  833. var meshID = meshes[meshIndex];
  834. var mesh = gltfRuntime.meshes[meshID];
  835. if (!mesh) {
  836. continue;
  837. }
  838. // Positions, normals and UVs
  839. for (var i = 0; i < mesh.primitives.length; i++) {
  840. // Temporary vertex data
  841. var tempVertexData = new BABYLON.VertexData();
  842. var primitive = mesh.primitives[i];
  843. if (primitive.mode !== 4) {
  844. // continue;
  845. }
  846. var attributes = primitive.attributes;
  847. var accessor = null;
  848. var buffer = null;
  849. // Set positions, normal and uvs
  850. for (var semantic in attributes) {
  851. // Link accessor and buffer view
  852. accessor = gltfRuntime.accessors[attributes[semantic]];
  853. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  854. if (semantic === "NORMAL") {
  855. tempVertexData.normals = new Float32Array(buffer.length);
  856. tempVertexData.normals.set(buffer);
  857. }
  858. else if (semantic === "POSITION") {
  859. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  860. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  861. for (var j = 0; j < buffer.length; j += 4) {
  862. tempVertexData.positions[j] = buffer[j];
  863. tempVertexData.positions[j + 1] = buffer[j + 1];
  864. tempVertexData.positions[j + 2] = buffer[j + 2];
  865. }
  866. }
  867. else {
  868. tempVertexData.positions = new Float32Array(buffer.length);
  869. tempVertexData.positions.set(buffer);
  870. }
  871. verticesCounts.push(tempVertexData.positions.length);
  872. }
  873. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  874. var channel = Number(semantic.split("_")[1]);
  875. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  876. var uvs = new Float32Array(buffer.length);
  877. uvs.set(buffer);
  878. normalizeUVs(uvs);
  879. tempVertexData.set(uvs, uvKind);
  880. }
  881. else if (semantic === "JOINT") {
  882. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  883. tempVertexData.matricesIndices.set(buffer);
  884. }
  885. else if (semantic === "WEIGHT") {
  886. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  887. tempVertexData.matricesWeights.set(buffer);
  888. }
  889. else if (semantic === "COLOR") {
  890. tempVertexData.colors = new Float32Array(buffer.length);
  891. tempVertexData.colors.set(buffer);
  892. }
  893. }
  894. // Indices
  895. accessor = gltfRuntime.accessors[primitive.indices];
  896. if (accessor) {
  897. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  898. tempVertexData.indices = new Int32Array(buffer.length);
  899. tempVertexData.indices.set(buffer);
  900. indexCounts.push(tempVertexData.indices.length);
  901. }
  902. else {
  903. // Set indices on the fly
  904. var indices = [];
  905. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  906. indices.push(j);
  907. }
  908. tempVertexData.indices = new Int32Array(indices);
  909. indexCounts.push(tempVertexData.indices.length);
  910. }
  911. vertexData.merge(tempVertexData);
  912. tempVertexData = undefined;
  913. // Sub material
  914. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  915. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  916. // Update vertices start and index start
  917. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  918. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  919. }
  920. }
  921. // Apply geometry
  922. geometry.setAllVerticesData(vertexData, false);
  923. newMesh.computeWorldMatrix(true);
  924. // Apply submeshes
  925. newMesh.subMeshes = [];
  926. var index = 0;
  927. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  928. var meshID = meshes[meshIndex];
  929. var mesh = gltfRuntime.meshes[meshID];
  930. if (!mesh) {
  931. continue;
  932. }
  933. for (var i = 0; i < mesh.primitives.length; i++) {
  934. if (mesh.primitives[i].mode !== 4) {
  935. //continue;
  936. }
  937. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  938. index++;
  939. }
  940. }
  941. // Finish
  942. return newMesh;
  943. };
  944. /**
  945. * Configure node transformation from position, rotation and scaling
  946. */
  947. var configureNode = function (newNode, position, rotation, scaling) {
  948. if (newNode.position) {
  949. newNode.position = position;
  950. }
  951. if (newNode.rotationQuaternion || newNode.rotation) {
  952. newNode.rotationQuaternion = rotation;
  953. }
  954. if (newNode.scaling) {
  955. newNode.scaling = scaling;
  956. }
  957. };
  958. /**
  959. * Configures node from transformation matrix
  960. */
  961. var configureNodeFromMatrix = function (newNode, node, parent) {
  962. if (node.matrix) {
  963. var position = new BABYLON.Vector3(0, 0, 0);
  964. var rotation = new BABYLON.Quaternion();
  965. var scaling = new BABYLON.Vector3(0, 0, 0);
  966. var mat = BABYLON.Matrix.FromArray(node.matrix);
  967. mat.decompose(scaling, rotation, position);
  968. configureNode(newNode, position, rotation, scaling);
  969. }
  970. else {
  971. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  972. }
  973. newNode.computeWorldMatrix(true);
  974. };
  975. /**
  976. * Imports a node
  977. */
  978. var importNode = function (gltfRuntime, node, id, parent) {
  979. var lastNode = null;
  980. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  981. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  982. return null;
  983. }
  984. }
  985. // Meshes
  986. if (node.skin) {
  987. if (node.meshes) {
  988. var skin = gltfRuntime.skins[node.skin];
  989. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  990. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  991. if (newMesh.skeleton === null) {
  992. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  993. if (!skin.babylonSkeleton) {
  994. skin.babylonSkeleton = newMesh.skeleton;
  995. }
  996. }
  997. lastNode = newMesh;
  998. }
  999. }
  1000. else if (node.meshes) {
  1001. /**
  1002. * Improve meshes property
  1003. */
  1004. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  1005. lastNode = newMesh;
  1006. }
  1007. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1008. var light = gltfRuntime.lights[node.light];
  1009. if (light) {
  1010. if (light.type === "ambient") {
  1011. var ambienLight = light[light.type];
  1012. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1013. hemiLight.name = node.name;
  1014. if (ambienLight.color) {
  1015. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  1016. }
  1017. lastNode = hemiLight;
  1018. }
  1019. else if (light.type === "directional") {
  1020. var directionalLight = light[light.type];
  1021. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1022. dirLight.name = node.name;
  1023. if (directionalLight.color) {
  1024. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  1025. }
  1026. lastNode = dirLight;
  1027. }
  1028. else if (light.type === "point") {
  1029. var pointLight = light[light.type];
  1030. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1031. ptLight.name = node.name;
  1032. if (pointLight.color) {
  1033. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  1034. }
  1035. lastNode = ptLight;
  1036. }
  1037. else if (light.type === "spot") {
  1038. var spotLight = light[light.type];
  1039. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  1040. spLight.name = node.name;
  1041. if (spotLight.color) {
  1042. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  1043. }
  1044. if (spotLight.fallOfAngle) {
  1045. spLight.angle = spotLight.fallOfAngle;
  1046. }
  1047. if (spotLight.fallOffExponent) {
  1048. spLight.exponent = spotLight.fallOffExponent;
  1049. }
  1050. lastNode = spLight;
  1051. }
  1052. }
  1053. }
  1054. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1055. var camera = gltfRuntime.cameras[node.camera];
  1056. if (camera) {
  1057. if (camera.type === "orthographic") {
  1058. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1059. orthoCamera.name = node.name;
  1060. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1061. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1062. lastNode = orthoCamera;
  1063. }
  1064. else if (camera.type === "perspective") {
  1065. var perspectiveCamera = camera[camera.type];
  1066. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1067. persCamera.name = node.name;
  1068. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1069. if (!perspectiveCamera.aspectRatio) {
  1070. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  1071. }
  1072. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  1073. persCamera.maxZ = perspectiveCamera.zfar;
  1074. persCamera.minZ = perspectiveCamera.znear;
  1075. }
  1076. lastNode = persCamera;
  1077. }
  1078. }
  1079. }
  1080. // Empty node
  1081. if (!node.jointName) {
  1082. if (node.babylonNode) {
  1083. return node.babylonNode;
  1084. }
  1085. else if (lastNode === null) {
  1086. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  1087. node.babylonNode = dummy;
  1088. lastNode = dummy;
  1089. }
  1090. }
  1091. if (lastNode !== null) {
  1092. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  1093. configureNodeFromMatrix(lastNode, node, parent);
  1094. }
  1095. else {
  1096. var translation = node.translation || [0, 0, 0];
  1097. var rotation = node.rotation || [0, 0, 0, 1];
  1098. var scale = node.scale || [1, 1, 1];
  1099. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  1100. }
  1101. lastNode.updateCache(true);
  1102. node.babylonNode = lastNode;
  1103. }
  1104. return lastNode;
  1105. };
  1106. /**
  1107. * Traverses nodes and creates them
  1108. */
  1109. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  1110. var node = gltfRuntime.nodes[id];
  1111. var newNode = null;
  1112. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  1113. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  1114. meshIncluded = true;
  1115. }
  1116. else {
  1117. meshIncluded = false;
  1118. }
  1119. }
  1120. else {
  1121. meshIncluded = true;
  1122. }
  1123. if (!node.jointName && meshIncluded) {
  1124. newNode = importNode(gltfRuntime, node, id, parent);
  1125. if (newNode !== null) {
  1126. newNode.id = id;
  1127. newNode.parent = parent;
  1128. }
  1129. }
  1130. if (node.children) {
  1131. for (var i = 0; i < node.children.length; i++) {
  1132. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  1133. }
  1134. }
  1135. };
  1136. /**
  1137. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  1138. */
  1139. var postLoad = function (gltfRuntime) {
  1140. // Nodes
  1141. var currentScene = gltfRuntime.currentScene;
  1142. if (currentScene) {
  1143. for (var i = 0; i < currentScene.nodes.length; i++) {
  1144. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1145. }
  1146. }
  1147. else {
  1148. for (var thing in gltfRuntime.scenes) {
  1149. currentScene = gltfRuntime.scenes[thing];
  1150. for (var i = 0; i < currentScene.nodes.length; i++) {
  1151. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1152. }
  1153. }
  1154. }
  1155. // Set animations
  1156. loadAnimations(gltfRuntime);
  1157. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  1158. var skeleton = gltfRuntime.scene.skeletons[i];
  1159. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1160. }
  1161. };
  1162. /**
  1163. * onBind shaderrs callback to set uniforms and matrices
  1164. */
  1165. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  1166. var materialValues = material.values || technique.parameters;
  1167. for (var unif in unTreatedUniforms) {
  1168. var uniform = unTreatedUniforms[unif];
  1169. var type = uniform.type;
  1170. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  1171. if (uniform.semantic && !uniform.source && !uniform.node) {
  1172. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1173. }
  1174. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1175. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  1176. if (source === null) {
  1177. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  1178. }
  1179. if (source === null) {
  1180. continue;
  1181. }
  1182. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1183. }
  1184. }
  1185. else {
  1186. var value = materialValues[technique.uniforms[unif]];
  1187. if (!value) {
  1188. continue;
  1189. }
  1190. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1191. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  1192. if (texture === null || texture === undefined) {
  1193. continue;
  1194. }
  1195. shaderMaterial.getEffect().setTexture(unif, texture);
  1196. }
  1197. else {
  1198. GLTF1.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  1199. }
  1200. }
  1201. }
  1202. onSuccess(shaderMaterial);
  1203. };
  1204. /**
  1205. * Prepare uniforms to send the only one time
  1206. * Loads the appropriate textures
  1207. */
  1208. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1209. var materialValues = material.values || technique.parameters;
  1210. var techniqueUniforms = technique.uniforms;
  1211. /**
  1212. * Prepare values here (not matrices)
  1213. */
  1214. for (var unif in unTreatedUniforms) {
  1215. var uniform = unTreatedUniforms[unif];
  1216. var type = uniform.type;
  1217. var value = materialValues[techniqueUniforms[unif]];
  1218. if (value === undefined) {
  1219. // In case the value is the same for all materials
  1220. value = uniform.value;
  1221. }
  1222. if (!value) {
  1223. continue;
  1224. }
  1225. var onLoadTexture = function (uniformName) {
  1226. return function (texture) {
  1227. if (uniform.value) {
  1228. // Static uniform
  1229. shaderMaterial.setTexture(uniformName, texture);
  1230. delete unTreatedUniforms[uniformName];
  1231. }
  1232. };
  1233. };
  1234. // Texture (sampler2D)
  1235. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1236. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  1237. }
  1238. else {
  1239. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1240. // Static uniform
  1241. delete unTreatedUniforms[unif];
  1242. }
  1243. }
  1244. }
  1245. };
  1246. /**
  1247. * Shader compilation failed
  1248. */
  1249. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1250. return function (effect, error) {
  1251. shaderMaterial.dispose(true);
  1252. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1253. };
  1254. };
  1255. /**
  1256. * Shader compilation success
  1257. */
  1258. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1259. return function (_) {
  1260. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1261. shaderMaterial.onBind = function (mesh) {
  1262. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1263. };
  1264. };
  1265. };
  1266. /**
  1267. * Returns the appropriate uniform if already handled by babylon
  1268. */
  1269. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1270. for (var unif in technique.uniforms) {
  1271. var uniform = technique.uniforms[unif];
  1272. var uniformParameter = technique.parameters[uniform];
  1273. if (tokenizer.currentIdentifier === unif) {
  1274. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1275. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1276. if (transformIndex !== -1) {
  1277. delete unTreatedUniforms[unif];
  1278. return babylonTransforms[transformIndex];
  1279. }
  1280. }
  1281. }
  1282. }
  1283. return tokenizer.currentIdentifier;
  1284. };
  1285. /**
  1286. * All shaders loaded. Create materials one by one
  1287. */
  1288. var importMaterials = function (gltfRuntime) {
  1289. // Create materials
  1290. for (var mat in gltfRuntime.materials) {
  1291. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1292. }
  1293. };
  1294. /**
  1295. * Implementation of the base glTF spec
  1296. */
  1297. var GLTFLoaderBase = /** @class */ (function () {
  1298. function GLTFLoaderBase() {
  1299. }
  1300. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1301. var gltfRuntime = {
  1302. extensions: {},
  1303. accessors: {},
  1304. buffers: {},
  1305. bufferViews: {},
  1306. meshes: {},
  1307. lights: {},
  1308. cameras: {},
  1309. nodes: {},
  1310. images: {},
  1311. textures: {},
  1312. shaders: {},
  1313. programs: {},
  1314. samplers: {},
  1315. techniques: {},
  1316. materials: {},
  1317. animations: {},
  1318. skins: {},
  1319. extensionsUsed: [],
  1320. scenes: {},
  1321. buffersCount: 0,
  1322. shaderscount: 0,
  1323. scene: scene,
  1324. rootUrl: rootUrl,
  1325. loadedBufferCount: 0,
  1326. loadedBufferViews: {},
  1327. loadedShaderCount: 0,
  1328. importOnlyMeshes: false,
  1329. dummyNodes: []
  1330. };
  1331. // Parse
  1332. if (parsedData.extensions) {
  1333. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1334. }
  1335. if (parsedData.extensionsUsed) {
  1336. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1337. }
  1338. if (parsedData.buffers) {
  1339. parseBuffers(parsedData.buffers, gltfRuntime);
  1340. }
  1341. if (parsedData.bufferViews) {
  1342. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1343. }
  1344. if (parsedData.accessors) {
  1345. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1346. }
  1347. if (parsedData.meshes) {
  1348. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1349. }
  1350. if (parsedData.lights) {
  1351. parseObject(parsedData.lights, "lights", gltfRuntime);
  1352. }
  1353. if (parsedData.cameras) {
  1354. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1355. }
  1356. if (parsedData.nodes) {
  1357. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1358. }
  1359. if (parsedData.images) {
  1360. parseObject(parsedData.images, "images", gltfRuntime);
  1361. }
  1362. if (parsedData.textures) {
  1363. parseObject(parsedData.textures, "textures", gltfRuntime);
  1364. }
  1365. if (parsedData.shaders) {
  1366. parseShaders(parsedData.shaders, gltfRuntime);
  1367. }
  1368. if (parsedData.programs) {
  1369. parseObject(parsedData.programs, "programs", gltfRuntime);
  1370. }
  1371. if (parsedData.samplers) {
  1372. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1373. }
  1374. if (parsedData.techniques) {
  1375. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1376. }
  1377. if (parsedData.materials) {
  1378. parseObject(parsedData.materials, "materials", gltfRuntime);
  1379. }
  1380. if (parsedData.animations) {
  1381. parseObject(parsedData.animations, "animations", gltfRuntime);
  1382. }
  1383. if (parsedData.skins) {
  1384. parseObject(parsedData.skins, "skins", gltfRuntime);
  1385. }
  1386. if (parsedData.scenes) {
  1387. gltfRuntime.scenes = parsedData.scenes;
  1388. }
  1389. if (parsedData.scene && parsedData.scenes) {
  1390. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1391. }
  1392. return gltfRuntime;
  1393. };
  1394. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1395. var buffer = gltfRuntime.buffers[id];
  1396. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  1397. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  1398. }
  1399. else {
  1400. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, null, true, function (request) {
  1401. onError(request.status + " " + request.statusText);
  1402. });
  1403. }
  1404. };
  1405. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1406. var texture = gltfRuntime.textures[id];
  1407. if (!texture || !texture.source) {
  1408. onError(null);
  1409. return;
  1410. }
  1411. if (texture.babylonTexture) {
  1412. onSuccess(null);
  1413. return;
  1414. }
  1415. var source = gltfRuntime.images[texture.source];
  1416. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  1417. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  1418. }
  1419. else {
  1420. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, function (request) {
  1421. onError(request.status + " " + request.statusText);
  1422. });
  1423. }
  1424. };
  1425. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1426. var texture = gltfRuntime.textures[id];
  1427. if (texture.babylonTexture) {
  1428. onSuccess(texture.babylonTexture);
  1429. return;
  1430. }
  1431. var sampler = gltfRuntime.samplers[texture.sampler];
  1432. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1433. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1434. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1435. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1436. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1437. var blob = new Blob([buffer]);
  1438. var blobURL = URL.createObjectURL(blob);
  1439. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1440. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1441. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  1442. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  1443. newTexture.name = id;
  1444. texture.babylonTexture = newTexture;
  1445. onSuccess(newTexture);
  1446. };
  1447. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1448. var shader = gltfRuntime.shaders[id];
  1449. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  1450. var shaderString = atob(shader.uri.split(",")[1]);
  1451. onSuccess(shaderString);
  1452. }
  1453. else {
  1454. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, function (request) {
  1455. onError(request.status + " " + request.statusText);
  1456. });
  1457. }
  1458. };
  1459. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1460. var material = gltfRuntime.materials[id];
  1461. var technique = gltfRuntime.techniques[material.technique];
  1462. if (!technique) {
  1463. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1464. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  1465. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1466. onSuccess(defaultMaterial);
  1467. return;
  1468. }
  1469. var program = gltfRuntime.programs[technique.program];
  1470. var states = technique.states;
  1471. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1472. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1473. var newVertexShader = "";
  1474. var newPixelShader = "";
  1475. var vertexTokenizer = new Tokenizer(vertexShader);
  1476. var pixelTokenizer = new Tokenizer(pixelShader);
  1477. var unTreatedUniforms = {};
  1478. var uniforms = [];
  1479. var attributes = [];
  1480. var samplers = [];
  1481. // Fill uniform, sampler2D and attributes
  1482. for (var unif in technique.uniforms) {
  1483. var uniform = technique.uniforms[unif];
  1484. var uniformParameter = technique.parameters[uniform];
  1485. unTreatedUniforms[unif] = uniformParameter;
  1486. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1487. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1488. if (transformIndex !== -1) {
  1489. uniforms.push(babylonTransforms[transformIndex]);
  1490. delete unTreatedUniforms[unif];
  1491. }
  1492. else {
  1493. uniforms.push(unif);
  1494. }
  1495. }
  1496. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  1497. samplers.push(unif);
  1498. }
  1499. else {
  1500. uniforms.push(unif);
  1501. }
  1502. }
  1503. for (var attr in technique.attributes) {
  1504. var attribute = technique.attributes[attr];
  1505. var attributeParameter = technique.parameters[attribute];
  1506. if (attributeParameter.semantic) {
  1507. attributes.push(getAttribute(attributeParameter));
  1508. }
  1509. }
  1510. // Configure vertex shader
  1511. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1512. var tokenType = vertexTokenizer.currentToken;
  1513. if (tokenType !== ETokenType.IDENTIFIER) {
  1514. newVertexShader += vertexTokenizer.currentString;
  1515. continue;
  1516. }
  1517. var foundAttribute = false;
  1518. for (var attr in technique.attributes) {
  1519. var attribute = technique.attributes[attr];
  1520. var attributeParameter = technique.parameters[attribute];
  1521. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1522. newVertexShader += getAttribute(attributeParameter);
  1523. foundAttribute = true;
  1524. break;
  1525. }
  1526. }
  1527. if (foundAttribute) {
  1528. continue;
  1529. }
  1530. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1531. }
  1532. // Configure pixel shader
  1533. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1534. var tokenType = pixelTokenizer.currentToken;
  1535. if (tokenType !== ETokenType.IDENTIFIER) {
  1536. newPixelShader += pixelTokenizer.currentString;
  1537. continue;
  1538. }
  1539. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1540. }
  1541. // Create shader material
  1542. var shaderPath = {
  1543. vertex: program.vertexShader + id,
  1544. fragment: program.fragmentShader + id
  1545. };
  1546. var options = {
  1547. attributes: attributes,
  1548. uniforms: uniforms,
  1549. samplers: samplers,
  1550. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1551. };
  1552. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1553. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1554. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1555. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1556. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1557. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1558. if (states && states.functions) {
  1559. var functions = states.functions;
  1560. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  1561. shaderMaterial.backFaceCulling = false;
  1562. }
  1563. var blendFunc = functions.blendFuncSeparate;
  1564. if (blendFunc) {
  1565. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1566. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1567. }
  1568. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1569. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  1570. }
  1571. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1572. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  1573. }
  1574. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1575. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  1576. }
  1577. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1578. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  1579. }
  1580. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1581. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  1582. }
  1583. }
  1584. }
  1585. };
  1586. return GLTFLoaderBase;
  1587. }());
  1588. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  1589. /**
  1590. * glTF V1 Loader
  1591. */
  1592. var GLTFLoader = /** @class */ (function () {
  1593. function GLTFLoader() {
  1594. }
  1595. GLTFLoader.RegisterExtension = function (extension) {
  1596. if (GLTFLoader.Extensions[extension.name]) {
  1597. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1598. return;
  1599. }
  1600. GLTFLoader.Extensions[extension.name] = extension;
  1601. };
  1602. GLTFLoader.prototype.dispose = function () {
  1603. // do nothing
  1604. };
  1605. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  1606. var _this = this;
  1607. scene.useRightHandedSystem = true;
  1608. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1609. gltfRuntime.importOnlyMeshes = true;
  1610. if (meshesNames === "") {
  1611. gltfRuntime.importMeshesNames = [];
  1612. }
  1613. else if (typeof meshesNames === "string") {
  1614. gltfRuntime.importMeshesNames = [meshesNames];
  1615. }
  1616. else if (meshesNames && !(meshesNames instanceof Array)) {
  1617. gltfRuntime.importMeshesNames = [meshesNames];
  1618. }
  1619. else {
  1620. gltfRuntime.importMeshesNames = [];
  1621. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1622. }
  1623. // Create nodes
  1624. _this._createNodes(gltfRuntime);
  1625. var meshes = new Array();
  1626. var skeletons = new Array();
  1627. // Fill arrays of meshes and skeletons
  1628. for (var nde in gltfRuntime.nodes) {
  1629. var node = gltfRuntime.nodes[nde];
  1630. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1631. meshes.push(node.babylonNode);
  1632. }
  1633. }
  1634. for (var skl in gltfRuntime.skins) {
  1635. var skin = gltfRuntime.skins[skl];
  1636. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1637. skeletons.push(skin.babylonSkeleton);
  1638. }
  1639. }
  1640. // Load buffers, shaders, materials, etc.
  1641. _this._loadBuffersAsync(gltfRuntime, function () {
  1642. _this._loadShadersAsync(gltfRuntime, function () {
  1643. importMaterials(gltfRuntime);
  1644. postLoad(gltfRuntime);
  1645. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1646. onSuccess(meshes, null, skeletons);
  1647. }
  1648. });
  1649. }, onProgress);
  1650. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1651. onSuccess(meshes, null, skeletons);
  1652. }
  1653. }, onError);
  1654. return true;
  1655. };
  1656. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  1657. var _this = this;
  1658. scene.useRightHandedSystem = true;
  1659. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1660. // Load runtime extensios
  1661. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  1662. // Create nodes
  1663. _this._createNodes(gltfRuntime);
  1664. // Load buffers, shaders, materials, etc.
  1665. _this._loadBuffersAsync(gltfRuntime, function () {
  1666. _this._loadShadersAsync(gltfRuntime, function () {
  1667. importMaterials(gltfRuntime);
  1668. postLoad(gltfRuntime);
  1669. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  1670. onSuccess();
  1671. }
  1672. });
  1673. });
  1674. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  1675. onSuccess();
  1676. }
  1677. }, onError);
  1678. }, onError);
  1679. };
  1680. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1681. var hasShaders = false;
  1682. var processShader = function (sha, shader) {
  1683. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1684. gltfRuntime.loadedShaderCount++;
  1685. if (shaderString) {
  1686. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1687. }
  1688. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1689. onload();
  1690. }
  1691. }, function () {
  1692. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1693. });
  1694. };
  1695. for (var sha in gltfRuntime.shaders) {
  1696. hasShaders = true;
  1697. var shader = gltfRuntime.shaders[sha];
  1698. if (shader) {
  1699. processShader.bind(this, sha, shader)();
  1700. }
  1701. else {
  1702. BABYLON.Tools.Error("No shader named: " + sha);
  1703. }
  1704. }
  1705. if (!hasShaders) {
  1706. onload();
  1707. }
  1708. };
  1709. ;
  1710. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  1711. var hasBuffers = false;
  1712. var processBuffer = function (buf, buffer) {
  1713. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  1714. gltfRuntime.loadedBufferCount++;
  1715. if (bufferView) {
  1716. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1717. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1718. }
  1719. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1720. }
  1721. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1722. onLoad();
  1723. }
  1724. }, function () {
  1725. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1726. });
  1727. };
  1728. for (var buf in gltfRuntime.buffers) {
  1729. hasBuffers = true;
  1730. var buffer = gltfRuntime.buffers[buf];
  1731. if (buffer) {
  1732. processBuffer.bind(this, buf, buffer)();
  1733. }
  1734. else {
  1735. BABYLON.Tools.Error("No buffer named: " + buf);
  1736. }
  1737. }
  1738. if (!hasBuffers) {
  1739. onLoad();
  1740. }
  1741. };
  1742. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  1743. var currentScene = gltfRuntime.currentScene;
  1744. if (currentScene) {
  1745. // Only one scene even if multiple scenes are defined
  1746. for (var i = 0; i < currentScene.nodes.length; i++) {
  1747. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1748. }
  1749. }
  1750. else {
  1751. // Load all scenes
  1752. for (var thing in gltfRuntime.scenes) {
  1753. currentScene = gltfRuntime.scenes[thing];
  1754. for (var i = 0; i < currentScene.nodes.length; i++) {
  1755. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1756. }
  1757. }
  1758. }
  1759. };
  1760. GLTFLoader.Extensions = {};
  1761. return GLTFLoader;
  1762. }());
  1763. GLTF1.GLTFLoader = GLTFLoader;
  1764. ;
  1765. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  1766. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  1767. })(BABYLON || (BABYLON = {}));
  1768. //# sourceMappingURL=babylon.glTFLoader.js.map
  1769. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1770. var BABYLON;
  1771. (function (BABYLON) {
  1772. var GLTF1;
  1773. (function (GLTF1) {
  1774. /**
  1775. * Utils functions for GLTF
  1776. */
  1777. var GLTFUtils = /** @class */ (function () {
  1778. function GLTFUtils() {
  1779. }
  1780. /**
  1781. * Sets the given "parameter" matrix
  1782. * @param scene: the {BABYLON.Scene} object
  1783. * @param source: the source node where to pick the matrix
  1784. * @param parameter: the GLTF technique parameter
  1785. * @param uniformName: the name of the shader's uniform
  1786. * @param shaderMaterial: the shader material
  1787. */
  1788. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  1789. var mat = null;
  1790. if (parameter.semantic === "MODEL") {
  1791. mat = source.getWorldMatrix();
  1792. }
  1793. else if (parameter.semantic === "PROJECTION") {
  1794. mat = scene.getProjectionMatrix();
  1795. }
  1796. else if (parameter.semantic === "VIEW") {
  1797. mat = scene.getViewMatrix();
  1798. }
  1799. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  1800. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  1801. }
  1802. else if (parameter.semantic === "MODELVIEW") {
  1803. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  1804. }
  1805. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  1806. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  1807. }
  1808. else if (parameter.semantic === "MODELINVERSE") {
  1809. mat = source.getWorldMatrix().invert();
  1810. }
  1811. else if (parameter.semantic === "VIEWINVERSE") {
  1812. mat = scene.getViewMatrix().invert();
  1813. }
  1814. else if (parameter.semantic === "PROJECTIONINVERSE") {
  1815. mat = scene.getProjectionMatrix().invert();
  1816. }
  1817. else if (parameter.semantic === "MODELVIEWINVERSE") {
  1818. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  1819. }
  1820. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  1821. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  1822. }
  1823. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  1824. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  1825. }
  1826. else {
  1827. debugger;
  1828. }
  1829. switch (parameter.type) {
  1830. case GLTF1.EParameterType.FLOAT_MAT2:
  1831. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  1832. break;
  1833. case GLTF1.EParameterType.FLOAT_MAT3:
  1834. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  1835. break;
  1836. case GLTF1.EParameterType.FLOAT_MAT4:
  1837. shaderMaterial.setMatrix(uniformName, mat);
  1838. break;
  1839. default: break;
  1840. }
  1841. };
  1842. /**
  1843. * Sets the given "parameter" matrix
  1844. * @param shaderMaterial: the shader material
  1845. * @param uniform: the name of the shader's uniform
  1846. * @param value: the value of the uniform
  1847. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  1848. */
  1849. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  1850. switch (type) {
  1851. case GLTF1.EParameterType.FLOAT:
  1852. shaderMaterial.setFloat(uniform, value);
  1853. return true;
  1854. case GLTF1.EParameterType.FLOAT_VEC2:
  1855. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  1856. return true;
  1857. case GLTF1.EParameterType.FLOAT_VEC3:
  1858. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  1859. return true;
  1860. case GLTF1.EParameterType.FLOAT_VEC4:
  1861. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  1862. return true;
  1863. default: return false;
  1864. }
  1865. };
  1866. /**
  1867. * If the uri is a base64 string
  1868. * @param uri: the uri to test
  1869. */
  1870. GLTFUtils.IsBase64 = function (uri) {
  1871. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1872. };
  1873. /**
  1874. * Decode the base64 uri
  1875. * @param uri: the uri to decode
  1876. */
  1877. GLTFUtils.DecodeBase64 = function (uri) {
  1878. var decodedString = atob(uri.split(",")[1]);
  1879. var bufferLength = decodedString.length;
  1880. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1881. for (var i = 0; i < bufferLength; i++) {
  1882. bufferView[i] = decodedString.charCodeAt(i);
  1883. }
  1884. return bufferView.buffer;
  1885. };
  1886. /**
  1887. * Returns the wrap mode of the texture
  1888. * @param mode: the mode value
  1889. */
  1890. GLTFUtils.GetWrapMode = function (mode) {
  1891. switch (mode) {
  1892. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1893. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1894. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1895. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1896. }
  1897. };
  1898. /**
  1899. * Returns the byte stride giving an accessor
  1900. * @param accessor: the GLTF accessor objet
  1901. */
  1902. GLTFUtils.GetByteStrideFromType = function (accessor) {
  1903. // Needs this function since "byteStride" isn't requiered in glTF format
  1904. var type = accessor.type;
  1905. switch (type) {
  1906. case "VEC2": return 2;
  1907. case "VEC3": return 3;
  1908. case "VEC4": return 4;
  1909. case "MAT2": return 4;
  1910. case "MAT3": return 9;
  1911. case "MAT4": return 16;
  1912. default: return 1;
  1913. }
  1914. };
  1915. /**
  1916. * Returns the texture filter mode giving a mode value
  1917. * @param mode: the filter mode value
  1918. */
  1919. GLTFUtils.GetTextureFilterMode = function (mode) {
  1920. switch (mode) {
  1921. case GLTF1.ETextureFilterType.LINEAR:
  1922. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  1923. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1924. case GLTF1.ETextureFilterType.NEAREST:
  1925. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1926. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1927. }
  1928. };
  1929. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  1930. var byteOffset = bufferView.byteOffset + byteOffset;
  1931. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  1932. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  1933. throw new Error("Buffer access is out of range");
  1934. }
  1935. var buffer = loadedBufferView.buffer;
  1936. byteOffset += loadedBufferView.byteOffset;
  1937. switch (componentType) {
  1938. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  1939. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  1940. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  1941. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  1942. default: return new Float32Array(buffer, byteOffset, byteLength);
  1943. }
  1944. };
  1945. /**
  1946. * Returns a buffer from its accessor
  1947. * @param gltfRuntime: the GLTF runtime
  1948. * @param accessor: the GLTF accessor
  1949. */
  1950. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  1951. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  1952. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  1953. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  1954. };
  1955. /**
  1956. * Decodes a buffer view into a string
  1957. * @param view: the buffer view
  1958. */
  1959. GLTFUtils.DecodeBufferToText = function (view) {
  1960. var result = "";
  1961. var length = view.byteLength;
  1962. for (var i = 0; i < length; ++i) {
  1963. result += String.fromCharCode(view[i]);
  1964. }
  1965. return result;
  1966. };
  1967. /**
  1968. * Returns the default material of gltf. Related to
  1969. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  1970. * @param scene: the Babylon.js scene
  1971. */
  1972. GLTFUtils.GetDefaultMaterial = function (scene) {
  1973. if (!GLTFUtils._DefaultMaterial) {
  1974. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  1975. "precision highp float;",
  1976. "",
  1977. "uniform mat4 worldView;",
  1978. "uniform mat4 projection;",
  1979. "",
  1980. "attribute vec3 position;",
  1981. "",
  1982. "void main(void)",
  1983. "{",
  1984. " gl_Position = projection * worldView * vec4(position, 1.0);",
  1985. "}"
  1986. ].join("\n");
  1987. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  1988. "precision highp float;",
  1989. "",
  1990. "uniform vec4 u_emission;",
  1991. "",
  1992. "void main(void)",
  1993. "{",
  1994. " gl_FragColor = u_emission;",
  1995. "}"
  1996. ].join("\n");
  1997. var shaderPath = {
  1998. vertex: "GLTFDefaultMaterial",
  1999. fragment: "GLTFDefaultMaterial"
  2000. };
  2001. var options = {
  2002. attributes: ["position"],
  2003. uniforms: ["worldView", "projection", "u_emission"],
  2004. samplers: new Array(),
  2005. needAlphaBlending: false
  2006. };
  2007. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  2008. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  2009. }
  2010. return GLTFUtils._DefaultMaterial;
  2011. };
  2012. // The GLTF default material
  2013. GLTFUtils._DefaultMaterial = null;
  2014. return GLTFUtils;
  2015. }());
  2016. GLTF1.GLTFUtils = GLTFUtils;
  2017. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2018. })(BABYLON || (BABYLON = {}));
  2019. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  2020. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2021. var BABYLON;
  2022. (function (BABYLON) {
  2023. var GLTF1;
  2024. (function (GLTF1) {
  2025. var GLTFLoaderExtension = /** @class */ (function () {
  2026. function GLTFLoaderExtension(name) {
  2027. this._name = name;
  2028. }
  2029. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  2030. get: function () {
  2031. return this._name;
  2032. },
  2033. enumerable: true,
  2034. configurable: true
  2035. });
  2036. /**
  2037. * Defines an override for loading the runtime
  2038. * Return true to stop further extensions from loading the runtime
  2039. */
  2040. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2041. return false;
  2042. };
  2043. /**
  2044. * Defines an onverride for creating gltf runtime
  2045. * Return true to stop further extensions from creating the runtime
  2046. */
  2047. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2048. return false;
  2049. };
  2050. /**
  2051. * Defines an override for loading buffers
  2052. * Return true to stop further extensions from loading this buffer
  2053. */
  2054. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2055. return false;
  2056. };
  2057. /**
  2058. * Defines an override for loading texture buffers
  2059. * Return true to stop further extensions from loading this texture data
  2060. */
  2061. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2062. return false;
  2063. };
  2064. /**
  2065. * Defines an override for creating textures
  2066. * Return true to stop further extensions from loading this texture
  2067. */
  2068. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2069. return false;
  2070. };
  2071. /**
  2072. * Defines an override for loading shader strings
  2073. * Return true to stop further extensions from loading this shader data
  2074. */
  2075. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2076. return false;
  2077. };
  2078. /**
  2079. * Defines an override for loading materials
  2080. * Return true to stop further extensions from loading this material
  2081. */
  2082. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2083. return false;
  2084. };
  2085. // ---------
  2086. // Utilities
  2087. // ---------
  2088. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2089. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2090. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  2091. }, function () {
  2092. setTimeout(function () {
  2093. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2094. });
  2095. });
  2096. };
  2097. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2098. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2099. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  2100. }, function () {
  2101. setTimeout(function () {
  2102. onSuccess();
  2103. });
  2104. });
  2105. };
  2106. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2107. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2108. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2109. }, function () {
  2110. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2111. });
  2112. };
  2113. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  2114. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  2115. };
  2116. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2117. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2118. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2119. }, function () {
  2120. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2121. });
  2122. };
  2123. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2124. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2125. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2126. }, function () {
  2127. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2128. });
  2129. };
  2130. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2131. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2132. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2133. }, function () {
  2134. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2135. });
  2136. };
  2137. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2138. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2139. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2140. }, function () {
  2141. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2142. });
  2143. };
  2144. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  2145. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  2146. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  2147. if (func(loaderExtension)) {
  2148. return;
  2149. }
  2150. }
  2151. defaultFunc();
  2152. };
  2153. return GLTFLoaderExtension;
  2154. }());
  2155. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  2156. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2157. })(BABYLON || (BABYLON = {}));
  2158. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2159. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2160. var __extends = (this && this.__extends) || (function () {
  2161. var extendStatics = Object.setPrototypeOf ||
  2162. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2163. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2164. return function (d, b) {
  2165. extendStatics(d, b);
  2166. function __() { this.constructor = d; }
  2167. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2168. };
  2169. })();
  2170. var BABYLON;
  2171. (function (BABYLON) {
  2172. var GLTF1;
  2173. (function (GLTF1) {
  2174. var BinaryExtensionBufferName = "binary_glTF";
  2175. ;
  2176. ;
  2177. var GLTFBinaryExtension = /** @class */ (function (_super) {
  2178. __extends(GLTFBinaryExtension, _super);
  2179. function GLTFBinaryExtension() {
  2180. return _super.call(this, "KHR_binary_glTF") || this;
  2181. }
  2182. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2183. var extensionsUsed = data.json.extensionsUsed;
  2184. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1) {
  2185. return false;
  2186. }
  2187. this._bin = data.bin;
  2188. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2189. return true;
  2190. };
  2191. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2192. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  2193. return false;
  2194. }
  2195. if (id !== BinaryExtensionBufferName) {
  2196. return false;
  2197. }
  2198. onSuccess(this._bin);
  2199. return true;
  2200. };
  2201. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2202. var texture = gltfRuntime.textures[id];
  2203. var source = gltfRuntime.images[texture.source];
  2204. if (!source.extensions || !(this.name in source.extensions)) {
  2205. return false;
  2206. }
  2207. var sourceExt = source.extensions[this.name];
  2208. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  2209. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2210. onSuccess(buffer);
  2211. return true;
  2212. };
  2213. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2214. var shader = gltfRuntime.shaders[id];
  2215. if (!shader.extensions || !(this.name in shader.extensions)) {
  2216. return false;
  2217. }
  2218. var binaryExtensionShader = shader.extensions[this.name];
  2219. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  2220. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2221. setTimeout(function () {
  2222. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  2223. onSuccess(shaderString);
  2224. });
  2225. return true;
  2226. };
  2227. return GLTFBinaryExtension;
  2228. }(GLTF1.GLTFLoaderExtension));
  2229. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  2230. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  2231. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2232. })(BABYLON || (BABYLON = {}));
  2233. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  2234. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2235. var __extends = (this && this.__extends) || (function () {
  2236. var extendStatics = Object.setPrototypeOf ||
  2237. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2238. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2239. return function (d, b) {
  2240. extendStatics(d, b);
  2241. function __() { this.constructor = d; }
  2242. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2243. };
  2244. })();
  2245. var BABYLON;
  2246. (function (BABYLON) {
  2247. var GLTF1;
  2248. (function (GLTF1) {
  2249. ;
  2250. ;
  2251. ;
  2252. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  2253. __extends(GLTFMaterialsCommonExtension, _super);
  2254. function GLTFMaterialsCommonExtension() {
  2255. return _super.call(this, "KHR_materials_common") || this;
  2256. }
  2257. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2258. if (!gltfRuntime.extensions)
  2259. return false;
  2260. var extension = gltfRuntime.extensions[this.name];
  2261. if (!extension)
  2262. return false;
  2263. // Create lights
  2264. var lights = extension.lights;
  2265. if (lights) {
  2266. for (var thing in lights) {
  2267. var light = lights[thing];
  2268. switch (light.type) {
  2269. case "ambient":
  2270. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  2271. var ambient = light.ambient;
  2272. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  2273. break;
  2274. case "point":
  2275. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  2276. var point = light.point;
  2277. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  2278. break;
  2279. case "directional":
  2280. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  2281. var directional = light.directional;
  2282. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  2283. break;
  2284. case "spot":
  2285. var spot = light.spot;
  2286. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), light.spot.fallOffAngle || Math.PI, light.spot.fallOffExponent || 0.0, gltfRuntime.scene);
  2287. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  2288. break;
  2289. default:
  2290. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  2291. break;
  2292. }
  2293. }
  2294. }
  2295. return false;
  2296. };
  2297. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2298. var material = gltfRuntime.materials[id];
  2299. if (!material || !material.extensions)
  2300. return false;
  2301. var extension = material.extensions[this.name];
  2302. if (!extension)
  2303. return false;
  2304. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2305. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2306. if (extension.technique === "CONSTANT") {
  2307. standardMaterial.disableLighting = true;
  2308. }
  2309. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2310. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2311. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2312. // Ambient
  2313. if (typeof extension.values.ambient === "string") {
  2314. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2315. }
  2316. else {
  2317. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2318. }
  2319. // Diffuse
  2320. if (typeof extension.values.diffuse === "string") {
  2321. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2322. }
  2323. else {
  2324. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2325. }
  2326. // Emission
  2327. if (typeof extension.values.emission === "string") {
  2328. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2329. }
  2330. else {
  2331. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2332. }
  2333. // Specular
  2334. if (typeof extension.values.specular === "string") {
  2335. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2336. }
  2337. else {
  2338. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2339. }
  2340. return true;
  2341. };
  2342. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2343. // Create buffer from texture url
  2344. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2345. // Create texture from buffer
  2346. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2347. }, onError);
  2348. };
  2349. return GLTFMaterialsCommonExtension;
  2350. }(GLTF1.GLTFLoaderExtension));
  2351. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  2352. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  2353. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2354. })(BABYLON || (BABYLON = {}));
  2355. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map