babylon.glTF1FileLoader.js 128 KB

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