babylon.glTF1FileLoader.js 117 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404
  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 && 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. if (!animation.channels || !animation.samplers) {
  475. continue;
  476. }
  477. var lastAnimation = null;
  478. for (var i = 0; i < animation.channels.length; i++) {
  479. // Get parameters and load buffers
  480. var channel = animation.channels[i];
  481. var sampler = animation.samplers[channel.sampler];
  482. if (!sampler) {
  483. continue;
  484. }
  485. var inputData = null;
  486. var outputData = null;
  487. if (animation.parameters) {
  488. inputData = animation.parameters[sampler.input];
  489. outputData = animation.parameters[sampler.output];
  490. }
  491. else {
  492. inputData = sampler.input;
  493. outputData = sampler.output;
  494. }
  495. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  496. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  497. var targetID = channel.target.id;
  498. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  499. if (targetNode === null) {
  500. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  501. }
  502. if (targetNode === null) {
  503. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  504. continue;
  505. }
  506. var isBone = targetNode instanceof BABYLON.Bone;
  507. // Get target path (position, rotation or scaling)
  508. var targetPath = channel.target.path;
  509. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  510. if (targetPathIndex !== -1) {
  511. targetPath = babylonAnimationPaths[targetPathIndex];
  512. }
  513. // Determine animation type
  514. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  515. if (!isBone) {
  516. if (targetPath === "rotationQuaternion") {
  517. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  518. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  519. }
  520. else {
  521. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  522. }
  523. }
  524. // Create animation and key frames
  525. var babylonAnimation = null;
  526. var keys = [];
  527. var arrayOffset = 0;
  528. var modifyKey = false;
  529. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  530. babylonAnimation = lastAnimation;
  531. modifyKey = true;
  532. }
  533. if (!modifyKey) {
  534. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  535. }
  536. // For each frame
  537. for (var j = 0; j < bufferInput.length; j++) {
  538. var value = null;
  539. if (targetPath === "rotationQuaternion") {
  540. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  541. arrayOffset += 4;
  542. }
  543. else {
  544. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  545. arrayOffset += 3;
  546. }
  547. if (isBone) {
  548. var bone = targetNode;
  549. var translation = BABYLON.Vector3.Zero();
  550. var rotationQuaternion = new BABYLON.Quaternion();
  551. var scaling = BABYLON.Vector3.Zero();
  552. // Warning on decompose
  553. var mat = bone.getBaseMatrix();
  554. if (modifyKey && lastAnimation) {
  555. mat = lastAnimation.getKeys()[j].value;
  556. }
  557. mat.decompose(scaling, rotationQuaternion, translation);
  558. if (targetPath === "position") {
  559. translation = value;
  560. }
  561. else if (targetPath === "rotationQuaternion") {
  562. rotationQuaternion = value;
  563. }
  564. else {
  565. scaling = value;
  566. }
  567. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  568. }
  569. if (!modifyKey) {
  570. keys.push({
  571. frame: bufferInput[j],
  572. value: value
  573. });
  574. }
  575. else if (lastAnimation) {
  576. lastAnimation.getKeys()[j].value = value;
  577. }
  578. }
  579. // Finish
  580. if (!modifyKey && babylonAnimation) {
  581. babylonAnimation.setKeys(keys);
  582. targetNode.animations.push(babylonAnimation);
  583. }
  584. lastAnimation = babylonAnimation;
  585. gltfRuntime.scene.stopAnimation(targetNode);
  586. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  587. }
  588. }
  589. };
  590. /**
  591. * Returns the bones transformation matrix
  592. */
  593. var configureBoneTransformation = function (node) {
  594. var mat = null;
  595. if (node.translation || node.rotation || node.scale) {
  596. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  597. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  598. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  599. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  600. }
  601. else {
  602. mat = BABYLON.Matrix.FromArray(node.matrix);
  603. }
  604. return mat;
  605. };
  606. /**
  607. * Returns the parent bone
  608. */
  609. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  610. // Try to find
  611. for (var i = 0; i < newSkeleton.bones.length; i++) {
  612. if (newSkeleton.bones[i].name === jointName) {
  613. return newSkeleton.bones[i];
  614. }
  615. }
  616. // Not found, search in gltf nodes
  617. var nodes = gltfRuntime.nodes;
  618. for (var nde in nodes) {
  619. var node = nodes[nde];
  620. if (!node.jointName) {
  621. continue;
  622. }
  623. var children = node.children;
  624. for (var i = 0; i < children.length; i++) {
  625. var child = gltfRuntime.nodes[children[i]];
  626. if (!child.jointName) {
  627. continue;
  628. }
  629. if (child.jointName === jointName) {
  630. var mat = configureBoneTransformation(node);
  631. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  632. bone.id = nde;
  633. return bone;
  634. }
  635. }
  636. }
  637. return null;
  638. };
  639. /**
  640. * Returns the appropriate root node
  641. */
  642. var getNodeToRoot = function (nodesToRoot, id) {
  643. for (var i = 0; i < nodesToRoot.length; i++) {
  644. var nodeToRoot = nodesToRoot[i];
  645. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  646. var child = nodeToRoot.node.children[j];
  647. if (child === id) {
  648. return nodeToRoot.bone;
  649. }
  650. }
  651. }
  652. return null;
  653. };
  654. /**
  655. * Returns the node with the joint name
  656. */
  657. var getJointNode = function (gltfRuntime, jointName) {
  658. var nodes = gltfRuntime.nodes;
  659. var node = nodes[jointName];
  660. if (node) {
  661. return {
  662. node: node,
  663. id: jointName
  664. };
  665. }
  666. for (var nde in nodes) {
  667. node = nodes[nde];
  668. if (node.jointName === jointName) {
  669. return {
  670. node: node,
  671. id: nde
  672. };
  673. }
  674. }
  675. return null;
  676. };
  677. /**
  678. * Checks if a nodes is in joints
  679. */
  680. var nodeIsInJoints = function (skins, id) {
  681. for (var i = 0; i < skins.jointNames.length; i++) {
  682. if (skins.jointNames[i] === id) {
  683. return true;
  684. }
  685. }
  686. return false;
  687. };
  688. /**
  689. * Fills the nodes to root for bones and builds hierarchy
  690. */
  691. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  692. // Creates nodes for root
  693. for (var nde in gltfRuntime.nodes) {
  694. var node = gltfRuntime.nodes[nde];
  695. var id = nde;
  696. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  697. continue;
  698. }
  699. // Create node to root bone
  700. var mat = configureBoneTransformation(node);
  701. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  702. bone.id = id;
  703. nodesToRoot.push({ bone: bone, node: node, id: id });
  704. }
  705. // Parenting
  706. for (var i = 0; i < nodesToRoot.length; i++) {
  707. var nodeToRoot = nodesToRoot[i];
  708. var children = nodeToRoot.node.children;
  709. for (var j = 0; j < children.length; j++) {
  710. var child = null;
  711. for (var k = 0; k < nodesToRoot.length; k++) {
  712. if (nodesToRoot[k].id === children[j]) {
  713. child = nodesToRoot[k];
  714. break;
  715. }
  716. }
  717. if (child) {
  718. child.bone._parent = nodeToRoot.bone;
  719. nodeToRoot.bone.children.push(child.bone);
  720. }
  721. }
  722. }
  723. };
  724. /**
  725. * Imports a skeleton
  726. */
  727. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  728. if (!newSkeleton) {
  729. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  730. }
  731. if (!skins.babylonSkeleton) {
  732. return newSkeleton;
  733. }
  734. // Find the root bones
  735. var nodesToRoot = [];
  736. var nodesToRootToAdd = [];
  737. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  738. newSkeleton.bones = [];
  739. // Joints
  740. for (var i = 0; i < skins.jointNames.length; i++) {
  741. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  742. if (!jointNode) {
  743. continue;
  744. }
  745. var node = jointNode.node;
  746. if (!node) {
  747. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  748. continue;
  749. }
  750. var id = jointNode.id;
  751. // Optimize, if the bone already exists...
  752. var existingBone = gltfRuntime.scene.getBoneByID(id);
  753. if (existingBone) {
  754. newSkeleton.bones.push(existingBone);
  755. continue;
  756. }
  757. // Search for parent bone
  758. var foundBone = false;
  759. var parentBone = null;
  760. for (var j = 0; j < i; j++) {
  761. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  762. if (!jointNode_1) {
  763. continue;
  764. }
  765. var joint = jointNode_1.node;
  766. if (!joint) {
  767. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  768. continue;
  769. }
  770. var children = joint.children;
  771. if (!children) {
  772. continue;
  773. }
  774. foundBone = false;
  775. for (var k = 0; k < children.length; k++) {
  776. if (children[k] === id) {
  777. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  778. foundBone = true;
  779. break;
  780. }
  781. }
  782. if (foundBone) {
  783. break;
  784. }
  785. }
  786. // Create bone
  787. var mat = configureBoneTransformation(node);
  788. if (!parentBone && nodesToRoot.length > 0) {
  789. parentBone = getNodeToRoot(nodesToRoot, id);
  790. if (parentBone) {
  791. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  792. nodesToRootToAdd.push(parentBone);
  793. }
  794. }
  795. }
  796. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  797. bone.id = id;
  798. }
  799. // Polish
  800. var bones = newSkeleton.bones;
  801. newSkeleton.bones = [];
  802. for (var i = 0; i < skins.jointNames.length; i++) {
  803. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  804. if (!jointNode) {
  805. continue;
  806. }
  807. for (var j = 0; j < bones.length; j++) {
  808. if (bones[j].id === jointNode.id) {
  809. newSkeleton.bones.push(bones[j]);
  810. break;
  811. }
  812. }
  813. }
  814. newSkeleton.prepare();
  815. // Finish
  816. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  817. newSkeleton.bones.push(nodesToRootToAdd[i]);
  818. }
  819. return newSkeleton;
  820. };
  821. /**
  822. * Imports a mesh and its geometries
  823. */
  824. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  825. if (!newMesh) {
  826. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  827. newMesh.id = id;
  828. }
  829. if (!node.babylonNode) {
  830. return newMesh;
  831. }
  832. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  833. if (!newMesh.material) {
  834. newMesh.material = multiMat;
  835. }
  836. var vertexData = new BABYLON.VertexData();
  837. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  838. var verticesStarts = new Array();
  839. var verticesCounts = new Array();
  840. var indexStarts = new Array();
  841. var indexCounts = new Array();
  842. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  843. var meshID = meshes[meshIndex];
  844. var mesh = gltfRuntime.meshes[meshID];
  845. if (!mesh) {
  846. continue;
  847. }
  848. // Positions, normals and UVs
  849. for (var i = 0; i < mesh.primitives.length; i++) {
  850. // Temporary vertex data
  851. var tempVertexData = new BABYLON.VertexData();
  852. var primitive = mesh.primitives[i];
  853. if (primitive.mode !== 4) {
  854. // continue;
  855. }
  856. var attributes = primitive.attributes;
  857. var accessor = null;
  858. var buffer = null;
  859. // Set positions, normal and uvs
  860. for (var semantic in attributes) {
  861. // Link accessor and buffer view
  862. accessor = gltfRuntime.accessors[attributes[semantic]];
  863. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  864. if (semantic === "NORMAL") {
  865. tempVertexData.normals = new Float32Array(buffer.length);
  866. tempVertexData.normals.set(buffer);
  867. }
  868. else if (semantic === "POSITION") {
  869. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  870. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  871. for (var j = 0; j < buffer.length; j += 4) {
  872. tempVertexData.positions[j] = buffer[j];
  873. tempVertexData.positions[j + 1] = buffer[j + 1];
  874. tempVertexData.positions[j + 2] = buffer[j + 2];
  875. }
  876. }
  877. else {
  878. tempVertexData.positions = new Float32Array(buffer.length);
  879. tempVertexData.positions.set(buffer);
  880. }
  881. verticesCounts.push(tempVertexData.positions.length);
  882. }
  883. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  884. var channel = Number(semantic.split("_")[1]);
  885. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  886. var uvs = new Float32Array(buffer.length);
  887. uvs.set(buffer);
  888. normalizeUVs(uvs);
  889. tempVertexData.set(uvs, uvKind);
  890. }
  891. else if (semantic === "JOINT") {
  892. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  893. tempVertexData.matricesIndices.set(buffer);
  894. }
  895. else if (semantic === "WEIGHT") {
  896. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  897. tempVertexData.matricesWeights.set(buffer);
  898. }
  899. else if (semantic === "COLOR") {
  900. tempVertexData.colors = new Float32Array(buffer.length);
  901. tempVertexData.colors.set(buffer);
  902. }
  903. }
  904. // Indices
  905. accessor = gltfRuntime.accessors[primitive.indices];
  906. if (accessor) {
  907. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  908. tempVertexData.indices = new Int32Array(buffer.length);
  909. tempVertexData.indices.set(buffer);
  910. indexCounts.push(tempVertexData.indices.length);
  911. }
  912. else {
  913. // Set indices on the fly
  914. var indices = [];
  915. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  916. indices.push(j);
  917. }
  918. tempVertexData.indices = new Int32Array(indices);
  919. indexCounts.push(tempVertexData.indices.length);
  920. }
  921. vertexData.merge(tempVertexData);
  922. // Sub material
  923. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  924. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  925. // Update vertices start and index start
  926. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  927. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  928. }
  929. }
  930. // Apply geometry
  931. geometry.setAllVerticesData(vertexData, false);
  932. newMesh.computeWorldMatrix(true);
  933. // Apply submeshes
  934. newMesh.subMeshes = [];
  935. var index = 0;
  936. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  937. var meshID = meshes[meshIndex];
  938. var mesh = gltfRuntime.meshes[meshID];
  939. if (!mesh) {
  940. continue;
  941. }
  942. for (var i = 0; i < mesh.primitives.length; i++) {
  943. if (mesh.primitives[i].mode !== 4) {
  944. //continue;
  945. }
  946. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  947. index++;
  948. }
  949. }
  950. // Finish
  951. return newMesh;
  952. };
  953. /**
  954. * Configure node transformation from position, rotation and scaling
  955. */
  956. var configureNode = function (newNode, position, rotation, scaling) {
  957. if (newNode.position) {
  958. newNode.position = position;
  959. }
  960. if (newNode.rotationQuaternion || newNode.rotation) {
  961. newNode.rotationQuaternion = rotation;
  962. }
  963. if (newNode.scaling) {
  964. newNode.scaling = scaling;
  965. }
  966. };
  967. /**
  968. * Configures node from transformation matrix
  969. */
  970. var configureNodeFromMatrix = function (newNode, node, parent) {
  971. if (node.matrix) {
  972. var position = new BABYLON.Vector3(0, 0, 0);
  973. var rotation = new BABYLON.Quaternion();
  974. var scaling = new BABYLON.Vector3(0, 0, 0);
  975. var mat = BABYLON.Matrix.FromArray(node.matrix);
  976. mat.decompose(scaling, rotation, position);
  977. configureNode(newNode, position, rotation, scaling);
  978. }
  979. else if (node.translation && node.rotation && node.scale) {
  980. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  981. }
  982. newNode.computeWorldMatrix(true);
  983. };
  984. /**
  985. * Imports a node
  986. */
  987. var importNode = function (gltfRuntime, node, id, parent) {
  988. var lastNode = null;
  989. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  990. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  991. return null;
  992. }
  993. }
  994. // Meshes
  995. if (node.skin) {
  996. if (node.meshes) {
  997. var skin = gltfRuntime.skins[node.skin];
  998. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  999. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  1000. if (newMesh.skeleton === null && skin.babylonSkeleton) {
  1001. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  1002. if (!skin.babylonSkeleton) {
  1003. skin.babylonSkeleton = newMesh.skeleton;
  1004. }
  1005. }
  1006. lastNode = newMesh;
  1007. }
  1008. }
  1009. else if (node.meshes) {
  1010. /**
  1011. * Improve meshes property
  1012. */
  1013. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  1014. lastNode = newMesh;
  1015. }
  1016. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1017. var light = gltfRuntime.lights[node.light];
  1018. if (light) {
  1019. if (light.type === "ambient") {
  1020. var ambienLight = light[light.type];
  1021. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1022. hemiLight.name = node.name || "";
  1023. if (ambienLight.color) {
  1024. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  1025. }
  1026. lastNode = hemiLight;
  1027. }
  1028. else if (light.type === "directional") {
  1029. var directionalLight = light[light.type];
  1030. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1031. dirLight.name = node.name || "";
  1032. if (directionalLight.color) {
  1033. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  1034. }
  1035. lastNode = dirLight;
  1036. }
  1037. else if (light.type === "point") {
  1038. var pointLight = light[light.type];
  1039. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1040. ptLight.name = node.name || "";
  1041. if (pointLight.color) {
  1042. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  1043. }
  1044. lastNode = ptLight;
  1045. }
  1046. else if (light.type === "spot") {
  1047. var spotLight = light[light.type];
  1048. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  1049. spLight.name = node.name || "";
  1050. if (spotLight.color) {
  1051. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  1052. }
  1053. if (spotLight.fallOfAngle) {
  1054. spLight.angle = spotLight.fallOfAngle;
  1055. }
  1056. if (spotLight.fallOffExponent) {
  1057. spLight.exponent = spotLight.fallOffExponent;
  1058. }
  1059. lastNode = spLight;
  1060. }
  1061. }
  1062. }
  1063. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1064. var camera = gltfRuntime.cameras[node.camera];
  1065. if (camera) {
  1066. if (camera.type === "orthographic") {
  1067. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1068. orthoCamera.name = node.name || "";
  1069. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1070. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1071. lastNode = orthoCamera;
  1072. }
  1073. else if (camera.type === "perspective") {
  1074. var perspectiveCamera = camera[camera.type];
  1075. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1076. persCamera.name = node.name || "";
  1077. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1078. if (!perspectiveCamera.aspectRatio) {
  1079. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  1080. }
  1081. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  1082. persCamera.maxZ = perspectiveCamera.zfar;
  1083. persCamera.minZ = perspectiveCamera.znear;
  1084. }
  1085. lastNode = persCamera;
  1086. }
  1087. }
  1088. }
  1089. // Empty node
  1090. if (!node.jointName) {
  1091. if (node.babylonNode) {
  1092. return node.babylonNode;
  1093. }
  1094. else if (lastNode === null) {
  1095. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1096. node.babylonNode = dummy;
  1097. lastNode = dummy;
  1098. }
  1099. }
  1100. if (lastNode !== null) {
  1101. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  1102. configureNodeFromMatrix(lastNode, node, parent);
  1103. }
  1104. else {
  1105. var translation = node.translation || [0, 0, 0];
  1106. var rotation = node.rotation || [0, 0, 0, 1];
  1107. var scale = node.scale || [1, 1, 1];
  1108. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  1109. }
  1110. lastNode.updateCache(true);
  1111. node.babylonNode = lastNode;
  1112. }
  1113. return lastNode;
  1114. };
  1115. /**
  1116. * Traverses nodes and creates them
  1117. */
  1118. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  1119. if (meshIncluded === void 0) { meshIncluded = false; }
  1120. var node = gltfRuntime.nodes[id];
  1121. var newNode = null;
  1122. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  1123. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  1124. meshIncluded = true;
  1125. }
  1126. else {
  1127. meshIncluded = false;
  1128. }
  1129. }
  1130. else {
  1131. meshIncluded = true;
  1132. }
  1133. if (!node.jointName && meshIncluded) {
  1134. newNode = importNode(gltfRuntime, node, id, parent);
  1135. if (newNode !== null) {
  1136. newNode.id = id;
  1137. newNode.parent = parent;
  1138. }
  1139. }
  1140. if (node.children) {
  1141. for (var i = 0; i < node.children.length; i++) {
  1142. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  1143. }
  1144. }
  1145. };
  1146. /**
  1147. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  1148. */
  1149. var postLoad = function (gltfRuntime) {
  1150. // Nodes
  1151. var currentScene = gltfRuntime.currentScene;
  1152. if (currentScene) {
  1153. for (var i = 0; i < currentScene.nodes.length; i++) {
  1154. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1155. }
  1156. }
  1157. else {
  1158. for (var thing in gltfRuntime.scenes) {
  1159. currentScene = gltfRuntime.scenes[thing];
  1160. for (var i = 0; i < currentScene.nodes.length; i++) {
  1161. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1162. }
  1163. }
  1164. }
  1165. // Set animations
  1166. loadAnimations(gltfRuntime);
  1167. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  1168. var skeleton = gltfRuntime.scene.skeletons[i];
  1169. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1170. }
  1171. };
  1172. /**
  1173. * onBind shaderrs callback to set uniforms and matrices
  1174. */
  1175. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  1176. var materialValues = material.values || technique.parameters;
  1177. for (var unif in unTreatedUniforms) {
  1178. var uniform = unTreatedUniforms[unif];
  1179. var type = uniform.type;
  1180. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  1181. if (uniform.semantic && !uniform.source && !uniform.node) {
  1182. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1183. }
  1184. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1185. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  1186. if (source === null) {
  1187. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  1188. }
  1189. if (source === null) {
  1190. continue;
  1191. }
  1192. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1193. }
  1194. }
  1195. else {
  1196. var value = materialValues[technique.uniforms[unif]];
  1197. if (!value) {
  1198. continue;
  1199. }
  1200. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1201. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  1202. if (texture === null || texture === undefined) {
  1203. continue;
  1204. }
  1205. shaderMaterial.getEffect().setTexture(unif, texture);
  1206. }
  1207. else {
  1208. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  1209. }
  1210. }
  1211. }
  1212. onSuccess(shaderMaterial);
  1213. };
  1214. /**
  1215. * Prepare uniforms to send the only one time
  1216. * Loads the appropriate textures
  1217. */
  1218. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1219. var materialValues = material.values || technique.parameters;
  1220. var techniqueUniforms = technique.uniforms;
  1221. /**
  1222. * Prepare values here (not matrices)
  1223. */
  1224. for (var unif in unTreatedUniforms) {
  1225. var uniform = unTreatedUniforms[unif];
  1226. var type = uniform.type;
  1227. var value = materialValues[techniqueUniforms[unif]];
  1228. if (value === undefined) {
  1229. // In case the value is the same for all materials
  1230. value = uniform.value;
  1231. }
  1232. if (!value) {
  1233. continue;
  1234. }
  1235. var onLoadTexture = function (uniformName) {
  1236. return function (texture) {
  1237. if (uniform.value && uniformName) {
  1238. // Static uniform
  1239. shaderMaterial.setTexture(uniformName, texture);
  1240. delete unTreatedUniforms[uniformName];
  1241. }
  1242. };
  1243. };
  1244. // Texture (sampler2D)
  1245. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1246. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  1247. }
  1248. else {
  1249. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1250. // Static uniform
  1251. delete unTreatedUniforms[unif];
  1252. }
  1253. }
  1254. }
  1255. };
  1256. /**
  1257. * Shader compilation failed
  1258. */
  1259. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1260. return function (effect, error) {
  1261. shaderMaterial.dispose(true);
  1262. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1263. };
  1264. };
  1265. /**
  1266. * Shader compilation success
  1267. */
  1268. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1269. return function (_) {
  1270. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1271. shaderMaterial.onBind = function (mesh) {
  1272. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1273. };
  1274. };
  1275. };
  1276. /**
  1277. * Returns the appropriate uniform if already handled by babylon
  1278. */
  1279. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1280. for (var unif in technique.uniforms) {
  1281. var uniform = technique.uniforms[unif];
  1282. var uniformParameter = technique.parameters[uniform];
  1283. if (tokenizer.currentIdentifier === unif) {
  1284. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1285. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1286. if (transformIndex !== -1) {
  1287. delete unTreatedUniforms[unif];
  1288. return babylonTransforms[transformIndex];
  1289. }
  1290. }
  1291. }
  1292. }
  1293. return tokenizer.currentIdentifier;
  1294. };
  1295. /**
  1296. * All shaders loaded. Create materials one by one
  1297. */
  1298. var importMaterials = function (gltfRuntime) {
  1299. // Create materials
  1300. for (var mat in gltfRuntime.materials) {
  1301. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1302. }
  1303. };
  1304. /**
  1305. * Implementation of the base glTF spec
  1306. */
  1307. var GLTFLoaderBase = /** @class */ (function () {
  1308. function GLTFLoaderBase() {
  1309. }
  1310. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1311. var gltfRuntime = {
  1312. extensions: {},
  1313. accessors: {},
  1314. buffers: {},
  1315. bufferViews: {},
  1316. meshes: {},
  1317. lights: {},
  1318. cameras: {},
  1319. nodes: {},
  1320. images: {},
  1321. textures: {},
  1322. shaders: {},
  1323. programs: {},
  1324. samplers: {},
  1325. techniques: {},
  1326. materials: {},
  1327. animations: {},
  1328. skins: {},
  1329. extensionsUsed: [],
  1330. scenes: {},
  1331. buffersCount: 0,
  1332. shaderscount: 0,
  1333. scene: scene,
  1334. rootUrl: rootUrl,
  1335. loadedBufferCount: 0,
  1336. loadedBufferViews: {},
  1337. loadedShaderCount: 0,
  1338. importOnlyMeshes: false,
  1339. dummyNodes: []
  1340. };
  1341. // Parse
  1342. if (parsedData.extensions) {
  1343. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1344. }
  1345. if (parsedData.extensionsUsed) {
  1346. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1347. }
  1348. if (parsedData.buffers) {
  1349. parseBuffers(parsedData.buffers, gltfRuntime);
  1350. }
  1351. if (parsedData.bufferViews) {
  1352. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1353. }
  1354. if (parsedData.accessors) {
  1355. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1356. }
  1357. if (parsedData.meshes) {
  1358. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1359. }
  1360. if (parsedData.lights) {
  1361. parseObject(parsedData.lights, "lights", gltfRuntime);
  1362. }
  1363. if (parsedData.cameras) {
  1364. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1365. }
  1366. if (parsedData.nodes) {
  1367. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1368. }
  1369. if (parsedData.images) {
  1370. parseObject(parsedData.images, "images", gltfRuntime);
  1371. }
  1372. if (parsedData.textures) {
  1373. parseObject(parsedData.textures, "textures", gltfRuntime);
  1374. }
  1375. if (parsedData.shaders) {
  1376. parseShaders(parsedData.shaders, gltfRuntime);
  1377. }
  1378. if (parsedData.programs) {
  1379. parseObject(parsedData.programs, "programs", gltfRuntime);
  1380. }
  1381. if (parsedData.samplers) {
  1382. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1383. }
  1384. if (parsedData.techniques) {
  1385. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1386. }
  1387. if (parsedData.materials) {
  1388. parseObject(parsedData.materials, "materials", gltfRuntime);
  1389. }
  1390. if (parsedData.animations) {
  1391. parseObject(parsedData.animations, "animations", gltfRuntime);
  1392. }
  1393. if (parsedData.skins) {
  1394. parseObject(parsedData.skins, "skins", gltfRuntime);
  1395. }
  1396. if (parsedData.scenes) {
  1397. gltfRuntime.scenes = parsedData.scenes;
  1398. }
  1399. if (parsedData.scene && parsedData.scenes) {
  1400. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1401. }
  1402. return gltfRuntime;
  1403. };
  1404. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1405. var buffer = gltfRuntime.buffers[id];
  1406. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  1407. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  1408. }
  1409. else {
  1410. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  1411. if (request) {
  1412. onError(request.status + " " + request.statusText);
  1413. }
  1414. });
  1415. }
  1416. };
  1417. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1418. var texture = gltfRuntime.textures[id];
  1419. if (!texture || !texture.source) {
  1420. onError("");
  1421. return;
  1422. }
  1423. if (texture.babylonTexture) {
  1424. onSuccess(null);
  1425. return;
  1426. }
  1427. var source = gltfRuntime.images[texture.source];
  1428. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  1429. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  1430. }
  1431. else {
  1432. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  1433. if (request) {
  1434. onError(request.status + " " + request.statusText);
  1435. }
  1436. });
  1437. }
  1438. };
  1439. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1440. var texture = gltfRuntime.textures[id];
  1441. if (texture.babylonTexture) {
  1442. onSuccess(texture.babylonTexture);
  1443. return;
  1444. }
  1445. var sampler = gltfRuntime.samplers[texture.sampler];
  1446. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1447. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1448. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1449. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1450. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1451. var blob = new Blob([buffer]);
  1452. var blobURL = URL.createObjectURL(blob);
  1453. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1454. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1455. if (sampler.wrapS !== undefined) {
  1456. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  1457. }
  1458. if (sampler.wrapT !== undefined) {
  1459. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  1460. }
  1461. newTexture.name = id;
  1462. texture.babylonTexture = newTexture;
  1463. onSuccess(newTexture);
  1464. };
  1465. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1466. var shader = gltfRuntime.shaders[id];
  1467. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  1468. var shaderString = atob(shader.uri.split(",")[1]);
  1469. onSuccess(shaderString);
  1470. }
  1471. else {
  1472. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  1473. if (request) {
  1474. onError(request.status + " " + request.statusText);
  1475. }
  1476. });
  1477. }
  1478. };
  1479. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1480. var material = gltfRuntime.materials[id];
  1481. if (!material.technique) {
  1482. if (onError) {
  1483. onError("No technique found.");
  1484. }
  1485. return;
  1486. }
  1487. var technique = gltfRuntime.techniques[material.technique];
  1488. if (!technique) {
  1489. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1490. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  1491. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1492. onSuccess(defaultMaterial);
  1493. return;
  1494. }
  1495. var program = gltfRuntime.programs[technique.program];
  1496. var states = technique.states;
  1497. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1498. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1499. var newVertexShader = "";
  1500. var newPixelShader = "";
  1501. var vertexTokenizer = new Tokenizer(vertexShader);
  1502. var pixelTokenizer = new Tokenizer(pixelShader);
  1503. var unTreatedUniforms = {};
  1504. var uniforms = [];
  1505. var attributes = [];
  1506. var samplers = [];
  1507. // Fill uniform, sampler2D and attributes
  1508. for (var unif in technique.uniforms) {
  1509. var uniform = technique.uniforms[unif];
  1510. var uniformParameter = technique.parameters[uniform];
  1511. unTreatedUniforms[unif] = uniformParameter;
  1512. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1513. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1514. if (transformIndex !== -1) {
  1515. uniforms.push(babylonTransforms[transformIndex]);
  1516. delete unTreatedUniforms[unif];
  1517. }
  1518. else {
  1519. uniforms.push(unif);
  1520. }
  1521. }
  1522. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  1523. samplers.push(unif);
  1524. }
  1525. else {
  1526. uniforms.push(unif);
  1527. }
  1528. }
  1529. for (var attr in technique.attributes) {
  1530. var attribute = technique.attributes[attr];
  1531. var attributeParameter = technique.parameters[attribute];
  1532. if (attributeParameter.semantic) {
  1533. attributes.push(getAttribute(attributeParameter));
  1534. }
  1535. }
  1536. // Configure vertex shader
  1537. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1538. var tokenType = vertexTokenizer.currentToken;
  1539. if (tokenType !== ETokenType.IDENTIFIER) {
  1540. newVertexShader += vertexTokenizer.currentString;
  1541. continue;
  1542. }
  1543. var foundAttribute = false;
  1544. for (var attr in technique.attributes) {
  1545. var attribute = technique.attributes[attr];
  1546. var attributeParameter = technique.parameters[attribute];
  1547. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1548. newVertexShader += getAttribute(attributeParameter);
  1549. foundAttribute = true;
  1550. break;
  1551. }
  1552. }
  1553. if (foundAttribute) {
  1554. continue;
  1555. }
  1556. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1557. }
  1558. // Configure pixel shader
  1559. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1560. var tokenType = pixelTokenizer.currentToken;
  1561. if (tokenType !== ETokenType.IDENTIFIER) {
  1562. newPixelShader += pixelTokenizer.currentString;
  1563. continue;
  1564. }
  1565. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1566. }
  1567. // Create shader material
  1568. var shaderPath = {
  1569. vertex: program.vertexShader + id,
  1570. fragment: program.fragmentShader + id
  1571. };
  1572. var options = {
  1573. attributes: attributes,
  1574. uniforms: uniforms,
  1575. samplers: samplers,
  1576. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1577. };
  1578. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1579. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1580. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1581. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1582. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1583. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1584. if (states && states.functions) {
  1585. var functions = states.functions;
  1586. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  1587. shaderMaterial.backFaceCulling = false;
  1588. }
  1589. var blendFunc = functions.blendFuncSeparate;
  1590. if (blendFunc) {
  1591. 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) {
  1592. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1593. }
  1594. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1595. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  1596. }
  1597. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1598. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  1599. }
  1600. 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) {
  1601. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  1602. }
  1603. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1604. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  1605. }
  1606. 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) {
  1607. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  1608. }
  1609. }
  1610. }
  1611. };
  1612. return GLTFLoaderBase;
  1613. }());
  1614. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  1615. /**
  1616. * glTF V1 Loader
  1617. */
  1618. var GLTFLoader = /** @class */ (function () {
  1619. function GLTFLoader() {
  1620. }
  1621. GLTFLoader.RegisterExtension = function (extension) {
  1622. if (GLTFLoader.Extensions[extension.name]) {
  1623. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1624. return;
  1625. }
  1626. GLTFLoader.Extensions[extension.name] = extension;
  1627. };
  1628. GLTFLoader.prototype.dispose = function () {
  1629. // do nothing
  1630. };
  1631. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  1632. var _this = this;
  1633. scene.useRightHandedSystem = true;
  1634. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1635. gltfRuntime.importOnlyMeshes = true;
  1636. if (meshesNames === "") {
  1637. gltfRuntime.importMeshesNames = [];
  1638. }
  1639. else if (typeof meshesNames === "string") {
  1640. gltfRuntime.importMeshesNames = [meshesNames];
  1641. }
  1642. else if (meshesNames && !(meshesNames instanceof Array)) {
  1643. gltfRuntime.importMeshesNames = [meshesNames];
  1644. }
  1645. else {
  1646. gltfRuntime.importMeshesNames = [];
  1647. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1648. }
  1649. // Create nodes
  1650. _this._createNodes(gltfRuntime);
  1651. var meshes = new Array();
  1652. var skeletons = new Array();
  1653. // Fill arrays of meshes and skeletons
  1654. for (var nde in gltfRuntime.nodes) {
  1655. var node = gltfRuntime.nodes[nde];
  1656. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1657. meshes.push(node.babylonNode);
  1658. }
  1659. }
  1660. for (var skl in gltfRuntime.skins) {
  1661. var skin = gltfRuntime.skins[skl];
  1662. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1663. skeletons.push(skin.babylonSkeleton);
  1664. }
  1665. }
  1666. // Load buffers, shaders, materials, etc.
  1667. _this._loadBuffersAsync(gltfRuntime, function () {
  1668. _this._loadShadersAsync(gltfRuntime, function () {
  1669. importMaterials(gltfRuntime);
  1670. postLoad(gltfRuntime);
  1671. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1672. onSuccess(meshes, null, skeletons);
  1673. }
  1674. });
  1675. }, onProgress);
  1676. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1677. onSuccess(meshes, null, skeletons);
  1678. }
  1679. }, onError);
  1680. return true;
  1681. };
  1682. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  1683. var _this = this;
  1684. scene.useRightHandedSystem = true;
  1685. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1686. // Load runtime extensios
  1687. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  1688. // Create nodes
  1689. _this._createNodes(gltfRuntime);
  1690. // Load buffers, shaders, materials, etc.
  1691. _this._loadBuffersAsync(gltfRuntime, function () {
  1692. _this._loadShadersAsync(gltfRuntime, function () {
  1693. importMaterials(gltfRuntime);
  1694. postLoad(gltfRuntime);
  1695. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  1696. onSuccess();
  1697. }
  1698. });
  1699. });
  1700. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  1701. onSuccess();
  1702. }
  1703. }, onError);
  1704. }, onError);
  1705. };
  1706. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1707. var hasShaders = false;
  1708. var processShader = function (sha, shader) {
  1709. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1710. gltfRuntime.loadedShaderCount++;
  1711. if (shaderString) {
  1712. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1713. }
  1714. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1715. onload();
  1716. }
  1717. }, function () {
  1718. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1719. });
  1720. };
  1721. for (var sha in gltfRuntime.shaders) {
  1722. hasShaders = true;
  1723. var shader = gltfRuntime.shaders[sha];
  1724. if (shader) {
  1725. processShader.bind(this, sha, shader)();
  1726. }
  1727. else {
  1728. BABYLON.Tools.Error("No shader named: " + sha);
  1729. }
  1730. }
  1731. if (!hasShaders) {
  1732. onload();
  1733. }
  1734. };
  1735. ;
  1736. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  1737. var hasBuffers = false;
  1738. var processBuffer = function (buf, buffer) {
  1739. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  1740. gltfRuntime.loadedBufferCount++;
  1741. if (bufferView) {
  1742. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1743. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1744. }
  1745. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1746. }
  1747. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1748. onLoad();
  1749. }
  1750. }, function () {
  1751. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1752. });
  1753. };
  1754. for (var buf in gltfRuntime.buffers) {
  1755. hasBuffers = true;
  1756. var buffer = gltfRuntime.buffers[buf];
  1757. if (buffer) {
  1758. processBuffer.bind(this, buf, buffer)();
  1759. }
  1760. else {
  1761. BABYLON.Tools.Error("No buffer named: " + buf);
  1762. }
  1763. }
  1764. if (!hasBuffers) {
  1765. onLoad();
  1766. }
  1767. };
  1768. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  1769. var currentScene = gltfRuntime.currentScene;
  1770. if (currentScene) {
  1771. // Only one scene even if multiple scenes are defined
  1772. for (var i = 0; i < currentScene.nodes.length; i++) {
  1773. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1774. }
  1775. }
  1776. else {
  1777. // Load all scenes
  1778. for (var thing in gltfRuntime.scenes) {
  1779. currentScene = gltfRuntime.scenes[thing];
  1780. for (var i = 0; i < currentScene.nodes.length; i++) {
  1781. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1782. }
  1783. }
  1784. }
  1785. };
  1786. GLTFLoader.Extensions = {};
  1787. return GLTFLoader;
  1788. }());
  1789. GLTF1.GLTFLoader = GLTFLoader;
  1790. ;
  1791. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  1792. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  1793. })(BABYLON || (BABYLON = {}));
  1794. //# sourceMappingURL=babylon.glTFLoader.js.map
  1795. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1796. var BABYLON;
  1797. (function (BABYLON) {
  1798. var GLTF1;
  1799. (function (GLTF1) {
  1800. /**
  1801. * Utils functions for GLTF
  1802. */
  1803. var GLTFUtils = /** @class */ (function () {
  1804. function GLTFUtils() {
  1805. }
  1806. /**
  1807. * Sets the given "parameter" matrix
  1808. * @param scene: the {BABYLON.Scene} object
  1809. * @param source: the source node where to pick the matrix
  1810. * @param parameter: the GLTF technique parameter
  1811. * @param uniformName: the name of the shader's uniform
  1812. * @param shaderMaterial: the shader material
  1813. */
  1814. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  1815. var mat = null;
  1816. if (parameter.semantic === "MODEL") {
  1817. mat = source.getWorldMatrix();
  1818. }
  1819. else if (parameter.semantic === "PROJECTION") {
  1820. mat = scene.getProjectionMatrix();
  1821. }
  1822. else if (parameter.semantic === "VIEW") {
  1823. mat = scene.getViewMatrix();
  1824. }
  1825. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  1826. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  1827. }
  1828. else if (parameter.semantic === "MODELVIEW") {
  1829. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  1830. }
  1831. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  1832. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  1833. }
  1834. else if (parameter.semantic === "MODELINVERSE") {
  1835. mat = source.getWorldMatrix().invert();
  1836. }
  1837. else if (parameter.semantic === "VIEWINVERSE") {
  1838. mat = scene.getViewMatrix().invert();
  1839. }
  1840. else if (parameter.semantic === "PROJECTIONINVERSE") {
  1841. mat = scene.getProjectionMatrix().invert();
  1842. }
  1843. else if (parameter.semantic === "MODELVIEWINVERSE") {
  1844. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  1845. }
  1846. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  1847. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  1848. }
  1849. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  1850. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  1851. }
  1852. else {
  1853. debugger;
  1854. }
  1855. if (mat) {
  1856. switch (parameter.type) {
  1857. case GLTF1.EParameterType.FLOAT_MAT2:
  1858. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  1859. break;
  1860. case GLTF1.EParameterType.FLOAT_MAT3:
  1861. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  1862. break;
  1863. case GLTF1.EParameterType.FLOAT_MAT4:
  1864. shaderMaterial.setMatrix(uniformName, mat);
  1865. break;
  1866. default: break;
  1867. }
  1868. }
  1869. };
  1870. /**
  1871. * Sets the given "parameter" matrix
  1872. * @param shaderMaterial: the shader material
  1873. * @param uniform: the name of the shader's uniform
  1874. * @param value: the value of the uniform
  1875. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  1876. */
  1877. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  1878. switch (type) {
  1879. case GLTF1.EParameterType.FLOAT:
  1880. shaderMaterial.setFloat(uniform, value);
  1881. return true;
  1882. case GLTF1.EParameterType.FLOAT_VEC2:
  1883. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  1884. return true;
  1885. case GLTF1.EParameterType.FLOAT_VEC3:
  1886. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  1887. return true;
  1888. case GLTF1.EParameterType.FLOAT_VEC4:
  1889. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  1890. return true;
  1891. default: return false;
  1892. }
  1893. };
  1894. /**
  1895. * If the uri is a base64 string
  1896. * @param uri: the uri to test
  1897. */
  1898. GLTFUtils.IsBase64 = function (uri) {
  1899. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1900. };
  1901. /**
  1902. * Decode the base64 uri
  1903. * @param uri: the uri to decode
  1904. */
  1905. GLTFUtils.DecodeBase64 = function (uri) {
  1906. var decodedString = atob(uri.split(",")[1]);
  1907. var bufferLength = decodedString.length;
  1908. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1909. for (var i = 0; i < bufferLength; i++) {
  1910. bufferView[i] = decodedString.charCodeAt(i);
  1911. }
  1912. return bufferView.buffer;
  1913. };
  1914. /**
  1915. * Returns the wrap mode of the texture
  1916. * @param mode: the mode value
  1917. */
  1918. GLTFUtils.GetWrapMode = function (mode) {
  1919. switch (mode) {
  1920. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1921. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1922. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1923. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1924. }
  1925. };
  1926. /**
  1927. * Returns the byte stride giving an accessor
  1928. * @param accessor: the GLTF accessor objet
  1929. */
  1930. GLTFUtils.GetByteStrideFromType = function (accessor) {
  1931. // Needs this function since "byteStride" isn't requiered in glTF format
  1932. var type = accessor.type;
  1933. switch (type) {
  1934. case "VEC2": return 2;
  1935. case "VEC3": return 3;
  1936. case "VEC4": return 4;
  1937. case "MAT2": return 4;
  1938. case "MAT3": return 9;
  1939. case "MAT4": return 16;
  1940. default: return 1;
  1941. }
  1942. };
  1943. /**
  1944. * Returns the texture filter mode giving a mode value
  1945. * @param mode: the filter mode value
  1946. */
  1947. GLTFUtils.GetTextureFilterMode = function (mode) {
  1948. switch (mode) {
  1949. case GLTF1.ETextureFilterType.LINEAR:
  1950. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  1951. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1952. case GLTF1.ETextureFilterType.NEAREST:
  1953. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1954. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1955. }
  1956. };
  1957. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  1958. var byteOffset = bufferView.byteOffset + byteOffset;
  1959. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  1960. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  1961. throw new Error("Buffer access is out of range");
  1962. }
  1963. var buffer = loadedBufferView.buffer;
  1964. byteOffset += loadedBufferView.byteOffset;
  1965. switch (componentType) {
  1966. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  1967. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  1968. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  1969. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  1970. default: return new Float32Array(buffer, byteOffset, byteLength);
  1971. }
  1972. };
  1973. /**
  1974. * Returns a buffer from its accessor
  1975. * @param gltfRuntime: the GLTF runtime
  1976. * @param accessor: the GLTF accessor
  1977. */
  1978. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  1979. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  1980. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  1981. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  1982. };
  1983. /**
  1984. * Decodes a buffer view into a string
  1985. * @param view: the buffer view
  1986. */
  1987. GLTFUtils.DecodeBufferToText = function (view) {
  1988. var result = "";
  1989. var length = view.byteLength;
  1990. for (var i = 0; i < length; ++i) {
  1991. result += String.fromCharCode(view[i]);
  1992. }
  1993. return result;
  1994. };
  1995. /**
  1996. * Returns the default material of gltf. Related to
  1997. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  1998. * @param scene: the Babylon.js scene
  1999. */
  2000. GLTFUtils.GetDefaultMaterial = function (scene) {
  2001. if (!GLTFUtils._DefaultMaterial) {
  2002. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  2003. "precision highp float;",
  2004. "",
  2005. "uniform mat4 worldView;",
  2006. "uniform mat4 projection;",
  2007. "",
  2008. "attribute vec3 position;",
  2009. "",
  2010. "void main(void)",
  2011. "{",
  2012. " gl_Position = projection * worldView * vec4(position, 1.0);",
  2013. "}"
  2014. ].join("\n");
  2015. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  2016. "precision highp float;",
  2017. "",
  2018. "uniform vec4 u_emission;",
  2019. "",
  2020. "void main(void)",
  2021. "{",
  2022. " gl_FragColor = u_emission;",
  2023. "}"
  2024. ].join("\n");
  2025. var shaderPath = {
  2026. vertex: "GLTFDefaultMaterial",
  2027. fragment: "GLTFDefaultMaterial"
  2028. };
  2029. var options = {
  2030. attributes: ["position"],
  2031. uniforms: ["worldView", "projection", "u_emission"],
  2032. samplers: new Array(),
  2033. needAlphaBlending: false
  2034. };
  2035. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  2036. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  2037. }
  2038. return GLTFUtils._DefaultMaterial;
  2039. };
  2040. // The GLTF default material
  2041. GLTFUtils._DefaultMaterial = null;
  2042. return GLTFUtils;
  2043. }());
  2044. GLTF1.GLTFUtils = GLTFUtils;
  2045. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2046. })(BABYLON || (BABYLON = {}));
  2047. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  2048. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2049. var BABYLON;
  2050. (function (BABYLON) {
  2051. var GLTF1;
  2052. (function (GLTF1) {
  2053. var GLTFLoaderExtension = /** @class */ (function () {
  2054. function GLTFLoaderExtension(name) {
  2055. this._name = name;
  2056. }
  2057. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  2058. get: function () {
  2059. return this._name;
  2060. },
  2061. enumerable: true,
  2062. configurable: true
  2063. });
  2064. /**
  2065. * Defines an override for loading the runtime
  2066. * Return true to stop further extensions from loading the runtime
  2067. */
  2068. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2069. return false;
  2070. };
  2071. /**
  2072. * Defines an onverride for creating gltf runtime
  2073. * Return true to stop further extensions from creating the runtime
  2074. */
  2075. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2076. return false;
  2077. };
  2078. /**
  2079. * Defines an override for loading buffers
  2080. * Return true to stop further extensions from loading this buffer
  2081. */
  2082. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2083. return false;
  2084. };
  2085. /**
  2086. * Defines an override for loading texture buffers
  2087. * Return true to stop further extensions from loading this texture data
  2088. */
  2089. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2090. return false;
  2091. };
  2092. /**
  2093. * Defines an override for creating textures
  2094. * Return true to stop further extensions from loading this texture
  2095. */
  2096. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2097. return false;
  2098. };
  2099. /**
  2100. * Defines an override for loading shader strings
  2101. * Return true to stop further extensions from loading this shader data
  2102. */
  2103. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2104. return false;
  2105. };
  2106. /**
  2107. * Defines an override for loading materials
  2108. * Return true to stop further extensions from loading this material
  2109. */
  2110. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2111. return false;
  2112. };
  2113. // ---------
  2114. // Utilities
  2115. // ---------
  2116. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2117. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2118. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  2119. }, function () {
  2120. setTimeout(function () {
  2121. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2122. });
  2123. });
  2124. };
  2125. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2126. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2127. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  2128. }, function () {
  2129. setTimeout(function () {
  2130. onSuccess();
  2131. });
  2132. });
  2133. };
  2134. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2135. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2136. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2137. }, function () {
  2138. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2139. });
  2140. };
  2141. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  2142. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  2143. };
  2144. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2145. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2146. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2147. }, function () {
  2148. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2149. });
  2150. };
  2151. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2152. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2153. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2154. }, function () {
  2155. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2156. });
  2157. };
  2158. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2159. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2160. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2161. }, function () {
  2162. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2163. });
  2164. };
  2165. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2166. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2167. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2168. }, function () {
  2169. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2170. });
  2171. };
  2172. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  2173. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  2174. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  2175. if (func(loaderExtension)) {
  2176. return;
  2177. }
  2178. }
  2179. defaultFunc();
  2180. };
  2181. return GLTFLoaderExtension;
  2182. }());
  2183. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  2184. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2185. })(BABYLON || (BABYLON = {}));
  2186. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2187. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2188. var __extends = (this && this.__extends) || (function () {
  2189. var extendStatics = Object.setPrototypeOf ||
  2190. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2191. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2192. return function (d, b) {
  2193. extendStatics(d, b);
  2194. function __() { this.constructor = d; }
  2195. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2196. };
  2197. })();
  2198. var BABYLON;
  2199. (function (BABYLON) {
  2200. var GLTF1;
  2201. (function (GLTF1) {
  2202. var BinaryExtensionBufferName = "binary_glTF";
  2203. ;
  2204. ;
  2205. var GLTFBinaryExtension = /** @class */ (function (_super) {
  2206. __extends(GLTFBinaryExtension, _super);
  2207. function GLTFBinaryExtension() {
  2208. return _super.call(this, "KHR_binary_glTF") || this;
  2209. }
  2210. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2211. var extensionsUsed = data.json.extensionsUsed;
  2212. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  2213. return false;
  2214. }
  2215. this._bin = data.bin;
  2216. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2217. return true;
  2218. };
  2219. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2220. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  2221. return false;
  2222. }
  2223. if (id !== BinaryExtensionBufferName) {
  2224. return false;
  2225. }
  2226. onSuccess(this._bin);
  2227. return true;
  2228. };
  2229. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2230. var texture = gltfRuntime.textures[id];
  2231. var source = gltfRuntime.images[texture.source];
  2232. if (!source.extensions || !(this.name in source.extensions)) {
  2233. return false;
  2234. }
  2235. var sourceExt = source.extensions[this.name];
  2236. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  2237. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2238. onSuccess(buffer);
  2239. return true;
  2240. };
  2241. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2242. var shader = gltfRuntime.shaders[id];
  2243. if (!shader.extensions || !(this.name in shader.extensions)) {
  2244. return false;
  2245. }
  2246. var binaryExtensionShader = shader.extensions[this.name];
  2247. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  2248. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2249. setTimeout(function () {
  2250. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  2251. onSuccess(shaderString);
  2252. });
  2253. return true;
  2254. };
  2255. return GLTFBinaryExtension;
  2256. }(GLTF1.GLTFLoaderExtension));
  2257. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  2258. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  2259. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2260. })(BABYLON || (BABYLON = {}));
  2261. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  2262. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2263. var __extends = (this && this.__extends) || (function () {
  2264. var extendStatics = Object.setPrototypeOf ||
  2265. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2266. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2267. return function (d, b) {
  2268. extendStatics(d, b);
  2269. function __() { this.constructor = d; }
  2270. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2271. };
  2272. })();
  2273. var BABYLON;
  2274. (function (BABYLON) {
  2275. var GLTF1;
  2276. (function (GLTF1) {
  2277. ;
  2278. ;
  2279. ;
  2280. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  2281. __extends(GLTFMaterialsCommonExtension, _super);
  2282. function GLTFMaterialsCommonExtension() {
  2283. return _super.call(this, "KHR_materials_common") || this;
  2284. }
  2285. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2286. if (!gltfRuntime.extensions)
  2287. return false;
  2288. var extension = gltfRuntime.extensions[this.name];
  2289. if (!extension)
  2290. return false;
  2291. // Create lights
  2292. var lights = extension.lights;
  2293. if (lights) {
  2294. for (var thing in lights) {
  2295. var light = lights[thing];
  2296. switch (light.type) {
  2297. case "ambient":
  2298. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  2299. var ambient = light.ambient;
  2300. if (ambient) {
  2301. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  2302. }
  2303. break;
  2304. case "point":
  2305. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  2306. var point = light.point;
  2307. if (point) {
  2308. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  2309. }
  2310. break;
  2311. case "directional":
  2312. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  2313. var directional = light.directional;
  2314. if (directional) {
  2315. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  2316. }
  2317. break;
  2318. case "spot":
  2319. var spot = light.spot;
  2320. if (spot) {
  2321. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  2322. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  2323. }
  2324. break;
  2325. default:
  2326. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  2327. break;
  2328. }
  2329. }
  2330. }
  2331. return false;
  2332. };
  2333. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2334. var material = gltfRuntime.materials[id];
  2335. if (!material || !material.extensions)
  2336. return false;
  2337. var extension = material.extensions[this.name];
  2338. if (!extension)
  2339. return false;
  2340. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2341. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2342. if (extension.technique === "CONSTANT") {
  2343. standardMaterial.disableLighting = true;
  2344. }
  2345. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2346. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2347. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2348. // Ambient
  2349. if (typeof extension.values.ambient === "string") {
  2350. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2351. }
  2352. else {
  2353. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2354. }
  2355. // Diffuse
  2356. if (typeof extension.values.diffuse === "string") {
  2357. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2358. }
  2359. else {
  2360. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2361. }
  2362. // Emission
  2363. if (typeof extension.values.emission === "string") {
  2364. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2365. }
  2366. else {
  2367. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2368. }
  2369. // Specular
  2370. if (typeof extension.values.specular === "string") {
  2371. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2372. }
  2373. else {
  2374. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2375. }
  2376. return true;
  2377. };
  2378. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2379. // Create buffer from texture url
  2380. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2381. // Create texture from buffer
  2382. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2383. }, onError);
  2384. };
  2385. return GLTFMaterialsCommonExtension;
  2386. }(GLTF1.GLTFLoaderExtension));
  2387. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  2388. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  2389. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2390. })(BABYLON || (BABYLON = {}));
  2391. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map