babylon.glTF1FileLoader.js 136 KB

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