babylon.glTF1FileLoader.js 117 KB

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