babylon.glTF1FileLoader.js 127 KB

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