babylon.glTF2FileLoader.js 173 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295
  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 when an error occurs.
  122. */
  123. this.onErrorObservable = new BABYLON.Observable();
  124. /**
  125. * Observable raised after the loader is disposed.
  126. */
  127. this.onDisposeObservable = new BABYLON.Observable();
  128. /**
  129. * Observable raised after a loader extension is created.
  130. * Set additional options for a loader extension in this event.
  131. */
  132. this.onExtensionLoadedObservable = new BABYLON.Observable();
  133. // #endregion
  134. this._loader = null;
  135. /**
  136. * Name of the loader ("gltf")
  137. */
  138. this.name = "gltf";
  139. /**
  140. * Supported file extensions of the loader (.gltf, .glb)
  141. */
  142. this.extensions = {
  143. ".gltf": { isBinary: false },
  144. ".glb": { isBinary: true }
  145. };
  146. this._logIndentLevel = 0;
  147. this._loggingEnabled = false;
  148. /** @hidden */
  149. this._log = this._logDisabled;
  150. this._capturePerformanceCounters = false;
  151. /** @hidden */
  152. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  153. /** @hidden */
  154. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  155. }
  156. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  157. /**
  158. * Raised when the asset has been parsed
  159. */
  160. set: function (callback) {
  161. if (this._onParsedObserver) {
  162. this.onParsedObservable.remove(this._onParsedObserver);
  163. }
  164. this._onParsedObserver = this.onParsedObservable.add(callback);
  165. },
  166. enumerable: true,
  167. configurable: true
  168. });
  169. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  170. /**
  171. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  172. */
  173. set: function (callback) {
  174. if (this._onMeshLoadedObserver) {
  175. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  176. }
  177. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  178. },
  179. enumerable: true,
  180. configurable: true
  181. });
  182. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  183. /**
  184. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  185. */
  186. set: function (callback) {
  187. if (this._onTextureLoadedObserver) {
  188. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  189. }
  190. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  191. },
  192. enumerable: true,
  193. configurable: true
  194. });
  195. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  196. /**
  197. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  198. */
  199. set: function (callback) {
  200. if (this._onMaterialLoadedObserver) {
  201. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  202. }
  203. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  204. },
  205. enumerable: true,
  206. configurable: true
  207. });
  208. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  209. /**
  210. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  211. */
  212. set: function (callback) {
  213. if (this._onCameraLoadedObserver) {
  214. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  215. }
  216. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  217. },
  218. enumerable: true,
  219. configurable: true
  220. });
  221. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  222. /**
  223. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  224. * For assets with LODs, raised when all of the LODs are complete.
  225. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  226. */
  227. set: function (callback) {
  228. if (this._onCompleteObserver) {
  229. this.onCompleteObservable.remove(this._onCompleteObserver);
  230. }
  231. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  232. },
  233. enumerable: true,
  234. configurable: true
  235. });
  236. Object.defineProperty(GLTFFileLoader.prototype, "onError", {
  237. /**
  238. * Callback raised when an error occurs.
  239. */
  240. set: function (callback) {
  241. if (this._onErrorObserver) {
  242. this.onErrorObservable.remove(this._onErrorObserver);
  243. }
  244. this._onErrorObserver = this.onErrorObservable.add(callback);
  245. },
  246. enumerable: true,
  247. configurable: true
  248. });
  249. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  250. /**
  251. * Callback raised after the loader is disposed.
  252. */
  253. set: function (callback) {
  254. if (this._onDisposeObserver) {
  255. this.onDisposeObservable.remove(this._onDisposeObserver);
  256. }
  257. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  258. },
  259. enumerable: true,
  260. configurable: true
  261. });
  262. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  263. /**
  264. * Callback raised after a loader extension is created.
  265. */
  266. set: function (callback) {
  267. if (this._onExtensionLoadedObserver) {
  268. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  269. }
  270. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  271. },
  272. enumerable: true,
  273. configurable: true
  274. });
  275. /**
  276. * Returns a promise that resolves when the asset is completely loaded.
  277. * @returns a promise that resolves when the asset is completely loaded.
  278. */
  279. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  280. var _this = this;
  281. return new Promise(function (resolve, reject) {
  282. _this.onCompleteObservable.addOnce(function () {
  283. resolve();
  284. });
  285. _this.onErrorObservable.addOnce(function (reason) {
  286. reject(reason);
  287. });
  288. });
  289. };
  290. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  291. /**
  292. * The loader state or null if the loader is not active.
  293. */
  294. get: function () {
  295. return this._loader ? this._loader.state : null;
  296. },
  297. enumerable: true,
  298. configurable: true
  299. });
  300. Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", {
  301. /**
  302. * Defines if the loader logging is enabled.
  303. */
  304. get: function () {
  305. return this._loggingEnabled;
  306. },
  307. set: function (value) {
  308. if (this._loggingEnabled === value) {
  309. return;
  310. }
  311. this._loggingEnabled = value;
  312. if (this._loggingEnabled) {
  313. this._log = this._logEnabled;
  314. }
  315. else {
  316. this._log = this._logDisabled;
  317. }
  318. },
  319. enumerable: true,
  320. configurable: true
  321. });
  322. Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", {
  323. /**
  324. * Defines if the loader should capture performance counters.
  325. */
  326. get: function () {
  327. return this._capturePerformanceCounters;
  328. },
  329. set: function (value) {
  330. if (this._capturePerformanceCounters === value) {
  331. return;
  332. }
  333. this._capturePerformanceCounters = value;
  334. if (this._capturePerformanceCounters) {
  335. this._startPerformanceCounter = this._startPerformanceCounterEnabled;
  336. this._endPerformanceCounter = this._endPerformanceCounterEnabled;
  337. }
  338. else {
  339. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  340. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  341. }
  342. },
  343. enumerable: true,
  344. configurable: true
  345. });
  346. /**
  347. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  348. */
  349. GLTFFileLoader.prototype.dispose = function () {
  350. if (this._loader) {
  351. this._loader.dispose();
  352. this._loader = null;
  353. }
  354. this._clear();
  355. this.onDisposeObservable.notifyObservers(undefined);
  356. this.onDisposeObservable.clear();
  357. };
  358. /** @hidden */
  359. GLTFFileLoader.prototype._clear = function () {
  360. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  361. this.onMeshLoadedObservable.clear();
  362. this.onTextureLoadedObservable.clear();
  363. this.onMaterialLoadedObservable.clear();
  364. this.onCameraLoadedObservable.clear();
  365. this.onCompleteObservable.clear();
  366. this.onExtensionLoadedObservable.clear();
  367. };
  368. /**
  369. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  370. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  371. * @param scene the scene the meshes should be added to
  372. * @param data the glTF data to load
  373. * @param rootUrl root url to load from
  374. * @param onProgress event that fires when loading progress has occured
  375. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  376. */
  377. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  378. var _this = this;
  379. return Promise.resolve().then(function () {
  380. var loaderData = _this._parse(data);
  381. _this._loader = _this._getLoader(loaderData);
  382. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  383. });
  384. };
  385. /**
  386. * Imports all objects from the loaded glTF data and adds them to the scene
  387. * @param scene the scene the objects should be added to
  388. * @param data the glTF data to load
  389. * @param rootUrl root url to load from
  390. * @param onProgress event that fires when loading progress has occured
  391. * @returns a promise which completes when objects have been loaded to the scene
  392. */
  393. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  394. var _this = this;
  395. return Promise.resolve().then(function () {
  396. var loaderData = _this._parse(data);
  397. _this._loader = _this._getLoader(loaderData);
  398. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  399. });
  400. };
  401. /**
  402. * Load into an asset container.
  403. * @param scene The scene to load into
  404. * @param data The data to import
  405. * @param rootUrl The root url for scene and resources
  406. * @param onProgress The callback when the load progresses
  407. * @returns The loaded asset container
  408. */
  409. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  410. var _this = this;
  411. return Promise.resolve().then(function () {
  412. var loaderData = _this._parse(data);
  413. _this._loader = _this._getLoader(loaderData);
  414. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  415. var container = new BABYLON.AssetContainer(scene);
  416. Array.prototype.push.apply(container.meshes, result.meshes);
  417. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  418. Array.prototype.push.apply(container.skeletons, result.skeletons);
  419. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  420. container.removeAllFromScene();
  421. return container;
  422. });
  423. });
  424. };
  425. /**
  426. * If the data string can be loaded directly.
  427. * @param data string contianing the file data
  428. * @returns if the data can be loaded directly
  429. */
  430. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  431. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  432. };
  433. /**
  434. * Instantiates a glTF file loader plugin.
  435. * @returns the created plugin
  436. */
  437. GLTFFileLoader.prototype.createPlugin = function () {
  438. return new GLTFFileLoader();
  439. };
  440. GLTFFileLoader.prototype._parse = function (data) {
  441. this._startPerformanceCounter("Parse");
  442. var parsedData;
  443. if (data instanceof ArrayBuffer) {
  444. this._log("Parsing binary");
  445. parsedData = this._parseBinary(data);
  446. }
  447. else {
  448. this._log("Parsing JSON");
  449. this._log("JSON length: " + data.length);
  450. parsedData = {
  451. json: JSON.parse(data),
  452. bin: null
  453. };
  454. }
  455. this.onParsedObservable.notifyObservers(parsedData);
  456. this.onParsedObservable.clear();
  457. this._endPerformanceCounter("Parse");
  458. return parsedData;
  459. };
  460. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  461. var asset = loaderData.json.asset || {};
  462. this._log("Asset version: " + asset.version);
  463. asset.minVersion && this._log("Asset minimum version: " + asset.minVersion);
  464. asset.generator && this._log("Asset generator: " + asset.generator);
  465. var version = GLTFFileLoader._parseVersion(asset.version);
  466. if (!version) {
  467. throw new Error("Invalid version: " + asset.version);
  468. }
  469. if (asset.minVersion !== undefined) {
  470. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  471. if (!minVersion) {
  472. throw new Error("Invalid minimum version: " + asset.minVersion);
  473. }
  474. if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
  475. throw new Error("Incompatible minimum version: " + asset.minVersion);
  476. }
  477. }
  478. var createLoaders = {
  479. 1: GLTFFileLoader._CreateGLTFLoaderV1,
  480. 2: GLTFFileLoader._CreateGLTFLoaderV2
  481. };
  482. var createLoader = createLoaders[version.major];
  483. if (!createLoader) {
  484. throw new Error("Unsupported version: " + asset.version);
  485. }
  486. return createLoader(this);
  487. };
  488. GLTFFileLoader.prototype._parseBinary = function (data) {
  489. var Binary = {
  490. Magic: 0x46546C67
  491. };
  492. this._log("Binary length: " + data.byteLength);
  493. var binaryReader = new BinaryReader(data);
  494. var magic = binaryReader.readUint32();
  495. if (magic !== Binary.Magic) {
  496. throw new Error("Unexpected magic: " + magic);
  497. }
  498. var version = binaryReader.readUint32();
  499. if (this.loggingEnabled) {
  500. this._log("Binary version: " + version);
  501. }
  502. switch (version) {
  503. case 1: return this._parseV1(binaryReader);
  504. case 2: return this._parseV2(binaryReader);
  505. }
  506. throw new Error("Unsupported version: " + version);
  507. };
  508. GLTFFileLoader.prototype._parseV1 = function (binaryReader) {
  509. var ContentFormat = {
  510. JSON: 0
  511. };
  512. var length = binaryReader.readUint32();
  513. if (length != binaryReader.getLength()) {
  514. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  515. }
  516. var contentLength = binaryReader.readUint32();
  517. var contentFormat = binaryReader.readUint32();
  518. var content;
  519. switch (contentFormat) {
  520. case ContentFormat.JSON: {
  521. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  522. break;
  523. }
  524. default: {
  525. throw new Error("Unexpected content format: " + contentFormat);
  526. }
  527. }
  528. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  529. var body = binaryReader.readUint8Array(bytesRemaining);
  530. return {
  531. json: content,
  532. bin: body
  533. };
  534. };
  535. GLTFFileLoader.prototype._parseV2 = function (binaryReader) {
  536. var ChunkFormat = {
  537. JSON: 0x4E4F534A,
  538. BIN: 0x004E4942
  539. };
  540. var length = binaryReader.readUint32();
  541. if (length !== binaryReader.getLength()) {
  542. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  543. }
  544. // JSON chunk
  545. var chunkLength = binaryReader.readUint32();
  546. var chunkFormat = binaryReader.readUint32();
  547. if (chunkFormat !== ChunkFormat.JSON) {
  548. throw new Error("First chunk format is not JSON");
  549. }
  550. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  551. // Look for BIN chunk
  552. var bin = null;
  553. while (binaryReader.getPosition() < binaryReader.getLength()) {
  554. var chunkLength_1 = binaryReader.readUint32();
  555. var chunkFormat_1 = binaryReader.readUint32();
  556. switch (chunkFormat_1) {
  557. case ChunkFormat.JSON: {
  558. throw new Error("Unexpected JSON chunk");
  559. }
  560. case ChunkFormat.BIN: {
  561. bin = binaryReader.readUint8Array(chunkLength_1);
  562. break;
  563. }
  564. default: {
  565. // ignore unrecognized chunkFormat
  566. binaryReader.skipBytes(chunkLength_1);
  567. break;
  568. }
  569. }
  570. }
  571. return {
  572. json: json,
  573. bin: bin
  574. };
  575. };
  576. GLTFFileLoader._parseVersion = function (version) {
  577. if (version === "1.0" || version === "1.0.1") {
  578. return {
  579. major: 1,
  580. minor: 0
  581. };
  582. }
  583. var match = (version + "").match(/^(\d+)\.(\d+)/);
  584. if (!match) {
  585. return null;
  586. }
  587. return {
  588. major: parseInt(match[1]),
  589. minor: parseInt(match[2])
  590. };
  591. };
  592. GLTFFileLoader._compareVersion = function (a, b) {
  593. if (a.major > b.major)
  594. return 1;
  595. if (a.major < b.major)
  596. return -1;
  597. if (a.minor > b.minor)
  598. return 1;
  599. if (a.minor < b.minor)
  600. return -1;
  601. return 0;
  602. };
  603. GLTFFileLoader._decodeBufferToText = function (buffer) {
  604. var result = "";
  605. var length = buffer.byteLength;
  606. for (var i = 0; i < length; i++) {
  607. result += String.fromCharCode(buffer[i]);
  608. }
  609. return result;
  610. };
  611. /** @hidden */
  612. GLTFFileLoader.prototype._logOpen = function (message) {
  613. this._log(message);
  614. this._logIndentLevel++;
  615. };
  616. /** @hidden */
  617. GLTFFileLoader.prototype._logClose = function () {
  618. --this._logIndentLevel;
  619. };
  620. GLTFFileLoader.prototype._logEnabled = function (message) {
  621. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  622. BABYLON.Tools.Log("" + spaces + message);
  623. };
  624. GLTFFileLoader.prototype._logDisabled = function (message) {
  625. };
  626. GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
  627. BABYLON.Tools.StartPerformanceCounter(counterName);
  628. };
  629. GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
  630. };
  631. GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
  632. BABYLON.Tools.EndPerformanceCounter(counterName);
  633. };
  634. GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
  635. };
  636. // #endregion
  637. // #region V1 options
  638. /**
  639. * 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.
  640. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  641. * Defaults to true.
  642. * @hidden
  643. */
  644. GLTFFileLoader.IncrementalLoading = true;
  645. /**
  646. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  647. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  648. * @hidden
  649. */
  650. GLTFFileLoader.HomogeneousCoordinates = false;
  651. GLTFFileLoader._logSpaces = " ";
  652. return GLTFFileLoader;
  653. }());
  654. BABYLON.GLTFFileLoader = GLTFFileLoader;
  655. var BinaryReader = /** @class */ (function () {
  656. function BinaryReader(arrayBuffer) {
  657. this._arrayBuffer = arrayBuffer;
  658. this._dataView = new DataView(arrayBuffer);
  659. this._byteOffset = 0;
  660. }
  661. BinaryReader.prototype.getPosition = function () {
  662. return this._byteOffset;
  663. };
  664. BinaryReader.prototype.getLength = function () {
  665. return this._arrayBuffer.byteLength;
  666. };
  667. BinaryReader.prototype.readUint32 = function () {
  668. var value = this._dataView.getUint32(this._byteOffset, true);
  669. this._byteOffset += 4;
  670. return value;
  671. };
  672. BinaryReader.prototype.readUint8Array = function (length) {
  673. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  674. this._byteOffset += length;
  675. return value;
  676. };
  677. BinaryReader.prototype.skipBytes = function (length) {
  678. this._byteOffset += length;
  679. };
  680. return BinaryReader;
  681. }());
  682. if (BABYLON.SceneLoader) {
  683. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  684. }
  685. })(BABYLON || (BABYLON = {}));
  686. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  687. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  688. /// <reference path="../../../../dist/preview release/glTF2Interface/babylon.glTF2Interface.d.ts"/>
  689. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  690. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  691. /**
  692. * Defines the module used to import/export glTF 2.0 assets
  693. */
  694. var BABYLON;
  695. (function (BABYLON) {
  696. var GLTF2;
  697. (function (GLTF2) {
  698. /** @hidden */
  699. var _ArrayItem = /** @class */ (function () {
  700. function _ArrayItem() {
  701. }
  702. _ArrayItem.Assign = function (values) {
  703. if (values) {
  704. for (var index = 0; index < values.length; index++) {
  705. values[index]._index = index;
  706. }
  707. }
  708. };
  709. return _ArrayItem;
  710. }());
  711. GLTF2._ArrayItem = _ArrayItem;
  712. /** @hidden */
  713. var GLTFLoader = /** @class */ (function () {
  714. function GLTFLoader(parent) {
  715. this._completePromises = new Array();
  716. this._disposed = false;
  717. this._state = null;
  718. this._extensions = {};
  719. this._defaultSampler = {};
  720. this._defaultBabylonMaterials = {};
  721. this._requests = new Array();
  722. this._parent = parent;
  723. }
  724. GLTFLoader._Register = function (name, factory) {
  725. if (GLTFLoader._ExtensionFactories[name]) {
  726. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  727. return;
  728. }
  729. GLTFLoader._ExtensionFactories[name] = factory;
  730. // Keep the order of registration so that extensions registered first are called first.
  731. GLTFLoader._ExtensionNames.push(name);
  732. };
  733. Object.defineProperty(GLTFLoader.prototype, "state", {
  734. get: function () {
  735. return this._state;
  736. },
  737. enumerable: true,
  738. configurable: true
  739. });
  740. GLTFLoader.prototype.dispose = function () {
  741. if (this._disposed) {
  742. return;
  743. }
  744. this._disposed = true;
  745. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  746. var request = _a[_i];
  747. request.abort();
  748. }
  749. this._requests.length = 0;
  750. delete this._gltf;
  751. delete this._babylonScene;
  752. this._completePromises.length = 0;
  753. for (var name_1 in this._extensions) {
  754. this._extensions[name_1].dispose();
  755. }
  756. this._extensions = {};
  757. delete this._rootBabylonMesh;
  758. delete this._progressCallback;
  759. this._parent._clear();
  760. };
  761. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  762. var _this = this;
  763. return Promise.resolve().then(function () {
  764. _this._babylonScene = scene;
  765. _this._rootUrl = rootUrl;
  766. _this._progressCallback = onProgress;
  767. _this._loadData(data);
  768. var nodes = null;
  769. if (meshesNames) {
  770. var nodeMap_1 = {};
  771. if (_this._gltf.nodes) {
  772. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  773. var node = _a[_i];
  774. if (node.name) {
  775. nodeMap_1[node.name] = node._index;
  776. }
  777. }
  778. }
  779. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  780. nodes = names.map(function (name) {
  781. var node = nodeMap_1[name];
  782. if (node === undefined) {
  783. throw new Error("Failed to find node '" + name + "'");
  784. }
  785. return node;
  786. });
  787. }
  788. return _this._loadAsync(nodes).then(function () {
  789. return {
  790. meshes: _this._getMeshes(),
  791. particleSystems: [],
  792. skeletons: _this._getSkeletons(),
  793. animationGroups: _this._getAnimationGroups()
  794. };
  795. });
  796. });
  797. };
  798. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  799. var _this = this;
  800. return Promise.resolve().then(function () {
  801. _this._babylonScene = scene;
  802. _this._rootUrl = rootUrl;
  803. _this._progressCallback = onProgress;
  804. _this._loadData(data);
  805. return _this._loadAsync(null);
  806. });
  807. };
  808. GLTFLoader.prototype._loadAsync = function (nodes) {
  809. var _this = this;
  810. return Promise.resolve().then(function () {
  811. _this._loadExtensions();
  812. _this._checkExtensions();
  813. var loadingToReadyCounterName = BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.LOADING] + " => " + BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.READY];
  814. var loadingToCompleteCounterName = BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.LOADING] + " => " + BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.COMPLETE];
  815. _this._parent._startPerformanceCounter(loadingToReadyCounterName);
  816. _this._parent._startPerformanceCounter(loadingToCompleteCounterName);
  817. _this._setState(BABYLON.GLTFLoaderState.LOADING);
  818. GLTF2.GLTFLoaderExtension._OnLoading(_this);
  819. var promises = new Array();
  820. if (nodes) {
  821. promises.push(_this._loadSceneAsync("#/nodes", { nodes: nodes, _index: -1 }));
  822. }
  823. else {
  824. var scene = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  825. promises.push(_this._loadSceneAsync("#/scenes/" + scene._index, scene));
  826. }
  827. if (_this._parent.compileMaterials) {
  828. promises.push(_this._compileMaterialsAsync());
  829. }
  830. if (_this._parent.compileShadowGenerators) {
  831. promises.push(_this._compileShadowGeneratorsAsync());
  832. }
  833. var resultPromise = Promise.all(promises).then(function () {
  834. _this._setState(BABYLON.GLTFLoaderState.READY);
  835. GLTF2.GLTFLoaderExtension._OnReady(_this);
  836. _this._startAnimations();
  837. });
  838. resultPromise.then(function () {
  839. _this._parent._endPerformanceCounter(loadingToReadyCounterName);
  840. BABYLON.Tools.SetImmediate(function () {
  841. if (!_this._disposed) {
  842. Promise.all(_this._completePromises).then(function () {
  843. _this._parent._endPerformanceCounter(loadingToCompleteCounterName);
  844. _this._setState(BABYLON.GLTFLoaderState.COMPLETE);
  845. _this._parent.onCompleteObservable.notifyObservers(undefined);
  846. _this._parent.onCompleteObservable.clear();
  847. _this.dispose();
  848. }, function (error) {
  849. _this._parent.onErrorObservable.notifyObservers(error);
  850. _this._parent.onErrorObservable.clear();
  851. _this.dispose();
  852. });
  853. }
  854. });
  855. });
  856. return resultPromise;
  857. }, function (error) {
  858. if (!_this._disposed) {
  859. _this._parent.onErrorObservable.notifyObservers(error);
  860. _this._parent.onErrorObservable.clear();
  861. _this.dispose();
  862. throw error;
  863. }
  864. });
  865. };
  866. GLTFLoader.prototype._loadData = function (data) {
  867. this._gltf = data.json;
  868. this._setupData();
  869. if (data.bin) {
  870. var buffers = this._gltf.buffers;
  871. if (buffers && buffers[0] && !buffers[0].uri) {
  872. var binaryBuffer = buffers[0];
  873. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  874. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  875. }
  876. binaryBuffer._data = Promise.resolve(data.bin);
  877. }
  878. else {
  879. BABYLON.Tools.Warn("Unexpected BIN chunk");
  880. }
  881. }
  882. };
  883. GLTFLoader.prototype._setupData = function () {
  884. _ArrayItem.Assign(this._gltf.accessors);
  885. _ArrayItem.Assign(this._gltf.animations);
  886. _ArrayItem.Assign(this._gltf.buffers);
  887. _ArrayItem.Assign(this._gltf.bufferViews);
  888. _ArrayItem.Assign(this._gltf.cameras);
  889. _ArrayItem.Assign(this._gltf.images);
  890. _ArrayItem.Assign(this._gltf.materials);
  891. _ArrayItem.Assign(this._gltf.meshes);
  892. _ArrayItem.Assign(this._gltf.nodes);
  893. _ArrayItem.Assign(this._gltf.samplers);
  894. _ArrayItem.Assign(this._gltf.scenes);
  895. _ArrayItem.Assign(this._gltf.skins);
  896. _ArrayItem.Assign(this._gltf.textures);
  897. if (this._gltf.nodes) {
  898. var nodeParents = {};
  899. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  900. var node = _a[_i];
  901. if (node.children) {
  902. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  903. var index = _c[_b];
  904. nodeParents[index] = node._index;
  905. }
  906. }
  907. }
  908. var rootNode = this._createRootNode();
  909. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  910. var node = _e[_d];
  911. var parentIndex = nodeParents[node._index];
  912. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  913. }
  914. }
  915. };
  916. GLTFLoader.prototype._loadExtensions = function () {
  917. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  918. var name_2 = _a[_i];
  919. var extension = GLTFLoader._ExtensionFactories[name_2](this);
  920. this._extensions[name_2] = extension;
  921. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  922. }
  923. this._parent.onExtensionLoadedObservable.clear();
  924. };
  925. GLTFLoader.prototype._checkExtensions = function () {
  926. if (this._gltf.extensionsRequired) {
  927. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  928. var name_3 = _a[_i];
  929. var extension = this._extensions[name_3];
  930. if (!extension || !extension.enabled) {
  931. throw new Error("Require extension " + name_3 + " is not available");
  932. }
  933. }
  934. }
  935. };
  936. GLTFLoader.prototype._setState = function (state) {
  937. this._state = state;
  938. this._parent._log(BABYLON.GLTFLoaderState[this._state]);
  939. };
  940. GLTFLoader.prototype._createRootNode = function () {
  941. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  942. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  943. switch (this._parent.coordinateSystemMode) {
  944. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  945. if (!this._babylonScene.useRightHandedSystem) {
  946. rootNode.rotation = [0, 1, 0, 0];
  947. rootNode.scale = [1, 1, -1];
  948. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  949. }
  950. break;
  951. }
  952. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  953. this._babylonScene.useRightHandedSystem = true;
  954. break;
  955. }
  956. default: {
  957. throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  958. }
  959. }
  960. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  961. return rootNode;
  962. };
  963. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  964. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  965. if (extensionPromise) {
  966. return extensionPromise;
  967. }
  968. var promises = new Array();
  969. this._parent._logOpen(context + " " + (scene.name || ""));
  970. if (scene.nodes) {
  971. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  972. var index = _a[_i];
  973. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  974. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  975. }
  976. }
  977. promises.push(this._loadAnimationsAsync());
  978. this._parent._logClose();
  979. return Promise.all(promises).then(function () { });
  980. };
  981. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  982. if (node._primitiveBabylonMeshes) {
  983. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  984. var babylonMesh = _a[_i];
  985. callback(babylonMesh);
  986. }
  987. }
  988. else {
  989. callback(node._babylonMesh);
  990. }
  991. };
  992. GLTFLoader.prototype._getMeshes = function () {
  993. var meshes = new Array();
  994. // Root mesh is always first.
  995. meshes.push(this._rootBabylonMesh);
  996. var nodes = this._gltf.nodes;
  997. if (nodes) {
  998. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  999. var node = nodes_1[_i];
  1000. if (node._babylonMesh) {
  1001. meshes.push(node._babylonMesh);
  1002. }
  1003. if (node._primitiveBabylonMeshes) {
  1004. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  1005. var babylonMesh = _b[_a];
  1006. meshes.push(babylonMesh);
  1007. }
  1008. }
  1009. }
  1010. }
  1011. return meshes;
  1012. };
  1013. GLTFLoader.prototype._getSkeletons = function () {
  1014. var skeletons = new Array();
  1015. var skins = this._gltf.skins;
  1016. if (skins) {
  1017. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  1018. var skin = skins_1[_i];
  1019. if (skin._babylonSkeleton) {
  1020. skeletons.push(skin._babylonSkeleton);
  1021. }
  1022. }
  1023. }
  1024. return skeletons;
  1025. };
  1026. GLTFLoader.prototype._getAnimationGroups = function () {
  1027. var animationGroups = new Array();
  1028. var animations = this._gltf.animations;
  1029. if (animations) {
  1030. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  1031. var animation = animations_1[_i];
  1032. if (animation._babylonAnimationGroup) {
  1033. animationGroups.push(animation._babylonAnimationGroup);
  1034. }
  1035. }
  1036. }
  1037. return animationGroups;
  1038. };
  1039. GLTFLoader.prototype._startAnimations = function () {
  1040. switch (this._parent.animationStartMode) {
  1041. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  1042. // do nothing
  1043. break;
  1044. }
  1045. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  1046. var babylonAnimationGroups = this._getAnimationGroups();
  1047. if (babylonAnimationGroups.length !== 0) {
  1048. babylonAnimationGroups[0].start(true);
  1049. }
  1050. break;
  1051. }
  1052. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  1053. var babylonAnimationGroups = this._getAnimationGroups();
  1054. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  1055. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  1056. babylonAnimationGroup.start(true);
  1057. }
  1058. break;
  1059. }
  1060. default: {
  1061. BABYLON.Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
  1062. return;
  1063. }
  1064. }
  1065. };
  1066. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  1067. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  1068. if (extensionPromise) {
  1069. return extensionPromise;
  1070. }
  1071. if (node._babylonMesh) {
  1072. throw new Error(context + ": Invalid recursive node hierarchy");
  1073. }
  1074. var promises = new Array();
  1075. this._parent._logOpen(context + " " + (node.name || ""));
  1076. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent ? node._parent._babylonMesh : null);
  1077. node._babylonMesh = babylonMesh;
  1078. babylonMesh.setEnabled(false);
  1079. GLTFLoader._LoadTransform(node, babylonMesh);
  1080. if (node.mesh != undefined) {
  1081. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  1082. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  1083. }
  1084. if (node.camera != undefined) {
  1085. var camera = GLTFLoader._GetProperty(context + "/camera", this._gltf.cameras, node.camera);
  1086. this._loadCamera("#/cameras/" + camera._index, camera, babylonMesh);
  1087. }
  1088. if (node.children) {
  1089. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  1090. var index = _a[_i];
  1091. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  1092. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  1093. }
  1094. }
  1095. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  1096. this._parent._logClose();
  1097. return Promise.all(promises).then(function () {
  1098. babylonMesh.setEnabled(true);
  1099. });
  1100. };
  1101. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  1102. var _this = this;
  1103. var promises = new Array();
  1104. this._parent._logOpen(context + " " + (mesh.name || ""));
  1105. var primitives = mesh.primitives;
  1106. if (!primitives || primitives.length === 0) {
  1107. throw new Error(context + ": Primitives are missing");
  1108. }
  1109. _ArrayItem.Assign(primitives);
  1110. if (primitives.length === 1) {
  1111. var primitive = primitives[0];
  1112. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  1113. }
  1114. else {
  1115. node._primitiveBabylonMeshes = [];
  1116. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  1117. var primitive = primitives_1[_i];
  1118. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  1119. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  1120. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  1121. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  1122. }
  1123. }
  1124. if (node.skin != undefined) {
  1125. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  1126. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  1127. }
  1128. this._parent._logClose();
  1129. return Promise.all(promises).then(function () {
  1130. _this._forEachPrimitive(node, function (babylonMesh) {
  1131. babylonMesh._refreshBoundingInfo(true);
  1132. });
  1133. });
  1134. };
  1135. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  1136. var _this = this;
  1137. var promises = new Array();
  1138. this._parent._logOpen("" + context);
  1139. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  1140. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  1141. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  1142. babylonGeometry.applyToMesh(babylonMesh);
  1143. });
  1144. }));
  1145. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  1146. if (primitive.material == undefined) {
  1147. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  1148. }
  1149. else {
  1150. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  1151. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  1152. babylonMesh.material = babylonMaterial;
  1153. }));
  1154. }
  1155. this._parent._logClose();
  1156. return Promise.all(promises).then(function () { });
  1157. };
  1158. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  1159. var _this = this;
  1160. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  1161. if (extensionPromise) {
  1162. return extensionPromise;
  1163. }
  1164. var attributes = primitive.attributes;
  1165. if (!attributes) {
  1166. throw new Error(context + ": Attributes are missing");
  1167. }
  1168. var promises = new Array();
  1169. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  1170. if (primitive.indices == undefined) {
  1171. babylonMesh.isUnIndexed = true;
  1172. }
  1173. else {
  1174. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  1175. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  1176. babylonGeometry.setIndices(data);
  1177. }));
  1178. }
  1179. var loadAttribute = function (attribute, kind, callback) {
  1180. if (attributes[attribute] == undefined) {
  1181. return;
  1182. }
  1183. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  1184. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  1185. babylonMesh._delayInfo.push(kind);
  1186. }
  1187. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  1188. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  1189. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  1190. }));
  1191. if (callback) {
  1192. callback(accessor);
  1193. }
  1194. };
  1195. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  1196. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  1197. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  1198. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  1199. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  1200. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  1201. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  1202. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  1203. if (accessor.type === "VEC4" /* VEC4 */) {
  1204. babylonMesh.hasVertexAlpha = true;
  1205. }
  1206. });
  1207. return Promise.all(promises).then(function () {
  1208. return babylonGeometry;
  1209. });
  1210. };
  1211. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  1212. if (!primitive.targets) {
  1213. return;
  1214. }
  1215. if (node._numMorphTargets == undefined) {
  1216. node._numMorphTargets = primitive.targets.length;
  1217. }
  1218. else if (primitive.targets.length !== node._numMorphTargets) {
  1219. throw new Error(context + ": Primitives do not have the same number of targets");
  1220. }
  1221. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  1222. for (var index = 0; index < primitive.targets.length; index++) {
  1223. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  1224. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  1225. // TODO: tell the target whether it has positions, normals, tangents
  1226. }
  1227. };
  1228. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  1229. if (!primitive.targets) {
  1230. return Promise.resolve();
  1231. }
  1232. var promises = new Array();
  1233. var morphTargetManager = babylonMesh.morphTargetManager;
  1234. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  1235. var babylonMorphTarget = morphTargetManager.getTarget(index);
  1236. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  1237. }
  1238. return Promise.all(promises).then(function () { });
  1239. };
  1240. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  1241. var _this = this;
  1242. var promises = new Array();
  1243. var loadAttribute = function (attribute, kind, setData) {
  1244. if (attributes[attribute] == undefined) {
  1245. return;
  1246. }
  1247. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  1248. if (!babylonVertexBuffer) {
  1249. return;
  1250. }
  1251. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  1252. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  1253. setData(babylonVertexBuffer, data);
  1254. }));
  1255. };
  1256. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  1257. babylonVertexBuffer.forEach(data.length, function (value, index) {
  1258. data[index] += value;
  1259. });
  1260. babylonMorphTarget.setPositions(data);
  1261. });
  1262. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  1263. babylonVertexBuffer.forEach(data.length, function (value, index) {
  1264. data[index] += value;
  1265. });
  1266. babylonMorphTarget.setNormals(data);
  1267. });
  1268. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  1269. var dataIndex = 0;
  1270. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  1271. // Tangent data for morph targets is stored as xyz delta.
  1272. // The vertexData.tangent is stored as xyzw.
  1273. // So we need to skip every fourth vertexData.tangent.
  1274. if (((index + 1) % 4) !== 0) {
  1275. data[dataIndex++] += value;
  1276. }
  1277. });
  1278. babylonMorphTarget.setTangents(data);
  1279. });
  1280. return Promise.all(promises).then(function () { });
  1281. };
  1282. GLTFLoader._LoadTransform = function (node, babylonNode) {
  1283. var position = BABYLON.Vector3.Zero();
  1284. var rotation = BABYLON.Quaternion.Identity();
  1285. var scaling = BABYLON.Vector3.One();
  1286. if (node.matrix) {
  1287. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  1288. matrix.decompose(scaling, rotation, position);
  1289. }
  1290. else {
  1291. if (node.translation)
  1292. position = BABYLON.Vector3.FromArray(node.translation);
  1293. if (node.rotation)
  1294. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  1295. if (node.scale)
  1296. scaling = BABYLON.Vector3.FromArray(node.scale);
  1297. }
  1298. babylonNode.position = position;
  1299. babylonNode.rotationQuaternion = rotation;
  1300. babylonNode.scaling = scaling;
  1301. };
  1302. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  1303. var _this = this;
  1304. var assignSkeleton = function (skeleton) {
  1305. _this._forEachPrimitive(node, function (babylonMesh) {
  1306. babylonMesh.skeleton = skeleton;
  1307. });
  1308. // Ignore the TRS of skinned nodes.
  1309. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  1310. node._babylonMesh.parent = _this._rootBabylonMesh;
  1311. node._babylonMesh.position = BABYLON.Vector3.Zero();
  1312. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  1313. node._babylonMesh.scaling = BABYLON.Vector3.One();
  1314. };
  1315. if (skin._loaded) {
  1316. return skin._loaded.then(function () {
  1317. assignSkeleton(skin._babylonSkeleton);
  1318. });
  1319. }
  1320. var skeletonId = "skeleton" + skin._index;
  1321. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  1322. skin._babylonSkeleton = babylonSkeleton;
  1323. this._loadBones(context, skin);
  1324. assignSkeleton(babylonSkeleton);
  1325. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  1326. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  1327. }));
  1328. };
  1329. GLTFLoader.prototype._loadBones = function (context, skin) {
  1330. var babylonBones = {};
  1331. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  1332. var index = _a[_i];
  1333. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  1334. this._loadBone(node, skin, babylonBones);
  1335. }
  1336. };
  1337. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  1338. var babylonBone = babylonBones[node._index];
  1339. if (babylonBone) {
  1340. return babylonBone;
  1341. }
  1342. var babylonParentBone = null;
  1343. if (node._parent && node._parent._babylonMesh !== this._rootBabylonMesh) {
  1344. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  1345. }
  1346. var boneIndex = skin.joints.indexOf(node._index);
  1347. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  1348. babylonBones[node._index] = babylonBone;
  1349. node._babylonBones = node._babylonBones || [];
  1350. node._babylonBones.push(babylonBone);
  1351. return babylonBone;
  1352. };
  1353. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  1354. if (skin.inverseBindMatrices == undefined) {
  1355. return Promise.resolve(null);
  1356. }
  1357. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  1358. return this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor);
  1359. };
  1360. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  1361. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  1362. var babylonBone = _a[_i];
  1363. var baseMatrix = BABYLON.Matrix.Identity();
  1364. var boneIndex = babylonBone._index;
  1365. if (inverseBindMatricesData && boneIndex !== -1) {
  1366. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  1367. baseMatrix.invertToRef(baseMatrix);
  1368. }
  1369. var babylonParentBone = babylonBone.getParent();
  1370. if (babylonParentBone) {
  1371. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  1372. }
  1373. babylonBone.updateMatrix(baseMatrix, false, false);
  1374. babylonBone._updateDifferenceMatrix(undefined, false);
  1375. }
  1376. };
  1377. GLTFLoader.prototype._getNodeMatrix = function (node) {
  1378. return node.matrix ?
  1379. BABYLON.Matrix.FromArray(node.matrix) :
  1380. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  1381. };
  1382. GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {
  1383. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);
  1384. babylonCamera.parent = babylonMesh;
  1385. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  1386. switch (camera.type) {
  1387. case "perspective" /* PERSPECTIVE */: {
  1388. var perspective = camera.perspective;
  1389. if (!perspective) {
  1390. throw new Error(context + ": Camera perspective properties are missing");
  1391. }
  1392. babylonCamera.fov = perspective.yfov;
  1393. babylonCamera.minZ = perspective.znear;
  1394. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  1395. break;
  1396. }
  1397. case "orthographic" /* ORTHOGRAPHIC */: {
  1398. if (!camera.orthographic) {
  1399. throw new Error(context + ": Camera orthographic properties are missing");
  1400. }
  1401. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1402. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  1403. babylonCamera.orthoRight = camera.orthographic.xmag;
  1404. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  1405. babylonCamera.orthoTop = camera.orthographic.ymag;
  1406. babylonCamera.minZ = camera.orthographic.znear;
  1407. babylonCamera.maxZ = camera.orthographic.zfar;
  1408. break;
  1409. }
  1410. default: {
  1411. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  1412. }
  1413. }
  1414. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  1415. };
  1416. GLTFLoader.prototype._loadAnimationsAsync = function () {
  1417. var animations = this._gltf.animations;
  1418. if (!animations) {
  1419. return Promise.resolve();
  1420. }
  1421. var promises = new Array();
  1422. for (var index = 0; index < animations.length; index++) {
  1423. var animation = animations[index];
  1424. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  1425. }
  1426. return Promise.all(promises).then(function () { });
  1427. };
  1428. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  1429. var _this = this;
  1430. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  1431. animation._babylonAnimationGroup = babylonAnimationGroup;
  1432. var promises = new Array();
  1433. _ArrayItem.Assign(animation.channels);
  1434. _ArrayItem.Assign(animation.samplers);
  1435. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  1436. var channel = _a[_i];
  1437. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  1438. }
  1439. return Promise.all(promises).then(function () {
  1440. babylonAnimationGroup.normalize(_this._parent._normalizeAnimationGroupsToBeginAtZero ? 0 : null);
  1441. });
  1442. };
  1443. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  1444. var _this = this;
  1445. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  1446. // Ignore animations that have no animation targets.
  1447. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  1448. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  1449. return Promise.resolve();
  1450. }
  1451. // Ignore animations targeting TRS of skinned nodes.
  1452. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  1453. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  1454. return Promise.resolve();
  1455. }
  1456. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  1457. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  1458. var targetPath;
  1459. var animationType;
  1460. switch (channel.target.path) {
  1461. case "translation" /* TRANSLATION */: {
  1462. targetPath = "position";
  1463. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1464. break;
  1465. }
  1466. case "rotation" /* ROTATION */: {
  1467. targetPath = "rotationQuaternion";
  1468. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  1469. break;
  1470. }
  1471. case "scale" /* SCALE */: {
  1472. targetPath = "scaling";
  1473. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1474. break;
  1475. }
  1476. case "weights" /* WEIGHTS */: {
  1477. targetPath = "influence";
  1478. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  1479. break;
  1480. }
  1481. default: {
  1482. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  1483. }
  1484. }
  1485. var outputBufferOffset = 0;
  1486. var getNextOutputValue;
  1487. switch (targetPath) {
  1488. case "position": {
  1489. getNextOutputValue = function () {
  1490. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  1491. outputBufferOffset += 3;
  1492. return value;
  1493. };
  1494. break;
  1495. }
  1496. case "rotationQuaternion": {
  1497. getNextOutputValue = function () {
  1498. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  1499. outputBufferOffset += 4;
  1500. return value;
  1501. };
  1502. break;
  1503. }
  1504. case "scaling": {
  1505. getNextOutputValue = function () {
  1506. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  1507. outputBufferOffset += 3;
  1508. return value;
  1509. };
  1510. break;
  1511. }
  1512. case "influence": {
  1513. getNextOutputValue = function () {
  1514. var value = new Array(targetNode._numMorphTargets);
  1515. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  1516. value[i] = data.output[outputBufferOffset++];
  1517. }
  1518. return value;
  1519. };
  1520. break;
  1521. }
  1522. }
  1523. var getNextKey;
  1524. switch (data.interpolation) {
  1525. case "STEP" /* STEP */: {
  1526. getNextKey = function (frameIndex) { return ({
  1527. frame: data.input[frameIndex],
  1528. value: getNextOutputValue(),
  1529. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  1530. }); };
  1531. break;
  1532. }
  1533. case "LINEAR" /* LINEAR */: {
  1534. getNextKey = function (frameIndex) { return ({
  1535. frame: data.input[frameIndex],
  1536. value: getNextOutputValue()
  1537. }); };
  1538. break;
  1539. }
  1540. case "CUBICSPLINE" /* CUBICSPLINE */: {
  1541. getNextKey = function (frameIndex) { return ({
  1542. frame: data.input[frameIndex],
  1543. inTangent: getNextOutputValue(),
  1544. value: getNextOutputValue(),
  1545. outTangent: getNextOutputValue()
  1546. }); };
  1547. break;
  1548. }
  1549. }
  1550. var keys = new Array(data.input.length);
  1551. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  1552. keys[frameIndex] = getNextKey(frameIndex);
  1553. }
  1554. if (targetPath === "influence") {
  1555. var _loop_1 = function (targetIndex) {
  1556. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  1557. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1558. babylonAnimation.setKeys(keys.map(function (key) { return ({
  1559. frame: key.frame,
  1560. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  1561. value: key.value[targetIndex],
  1562. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  1563. }); }));
  1564. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  1565. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  1566. var babylonAnimationClone = babylonAnimation.clone();
  1567. morphTarget.animations.push(babylonAnimationClone);
  1568. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  1569. });
  1570. };
  1571. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  1572. _loop_1(targetIndex);
  1573. }
  1574. }
  1575. else {
  1576. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  1577. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  1578. babylonAnimation.setKeys(keys);
  1579. if (targetNode._babylonBones) {
  1580. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  1581. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  1582. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  1583. babylonAnimationTarget.animations.push(babylonAnimation);
  1584. }
  1585. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  1586. }
  1587. else {
  1588. targetNode._babylonMesh.animations.push(babylonAnimation);
  1589. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  1590. }
  1591. }
  1592. });
  1593. };
  1594. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  1595. if (sampler._data) {
  1596. return sampler._data;
  1597. }
  1598. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  1599. switch (interpolation) {
  1600. case "STEP" /* STEP */:
  1601. case "LINEAR" /* LINEAR */:
  1602. case "CUBICSPLINE" /* CUBICSPLINE */: {
  1603. break;
  1604. }
  1605. default: {
  1606. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  1607. }
  1608. }
  1609. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  1610. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  1611. sampler._data = Promise.all([
  1612. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor),
  1613. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor)
  1614. ]).then(function (_a) {
  1615. var inputData = _a[0], outputData = _a[1];
  1616. return {
  1617. input: inputData,
  1618. interpolation: interpolation,
  1619. output: outputData,
  1620. };
  1621. });
  1622. return sampler._data;
  1623. };
  1624. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  1625. if (buffer._data) {
  1626. return buffer._data;
  1627. }
  1628. if (!buffer.uri) {
  1629. throw new Error(context + ": Uri is missing");
  1630. }
  1631. buffer._data = this._loadUriAsync(context, buffer.uri);
  1632. return buffer._data;
  1633. };
  1634. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  1635. if (bufferView._data) {
  1636. return bufferView._data;
  1637. }
  1638. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  1639. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  1640. try {
  1641. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  1642. }
  1643. catch (e) {
  1644. throw new Error(context + ": " + e.message);
  1645. }
  1646. });
  1647. return bufferView._data;
  1648. };
  1649. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  1650. if (accessor.type !== "SCALAR" /* SCALAR */) {
  1651. throw new Error(context + ": Invalid type " + accessor.type);
  1652. }
  1653. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  1654. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  1655. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  1656. throw new Error(context + ": Invalid component type " + accessor.componentType);
  1657. }
  1658. if (accessor._data) {
  1659. return accessor._data;
  1660. }
  1661. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  1662. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  1663. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  1664. });
  1665. return accessor._data;
  1666. };
  1667. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  1668. // TODO: support normalized and stride
  1669. var _this = this;
  1670. if (accessor.componentType !== 5126 /* FLOAT */) {
  1671. throw new Error("Invalid component type " + accessor.componentType);
  1672. }
  1673. if (accessor._data) {
  1674. return accessor._data;
  1675. }
  1676. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  1677. var length = numComponents * accessor.count;
  1678. if (accessor.bufferView == undefined) {
  1679. accessor._data = Promise.resolve(new Float32Array(length));
  1680. }
  1681. else {
  1682. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  1683. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  1684. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  1685. });
  1686. }
  1687. if (accessor.sparse) {
  1688. var sparse_1 = accessor.sparse;
  1689. accessor._data = accessor._data.then(function (data) {
  1690. var indicesBufferView = GLTFLoader._GetProperty(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView);
  1691. var valuesBufferView = GLTFLoader._GetProperty(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView);
  1692. return Promise.all([
  1693. _this._loadBufferViewAsync("#/bufferViews/" + indicesBufferView._index, indicesBufferView),
  1694. _this._loadBufferViewAsync("#/bufferViews/" + valuesBufferView._index, valuesBufferView)
  1695. ]).then(function (_a) {
  1696. var indicesData = _a[0], valuesData = _a[1];
  1697. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  1698. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  1699. var valuesIndex = 0;
  1700. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  1701. var dataIndex = indices[indicesIndex] * numComponents;
  1702. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  1703. data[dataIndex++] = values[valuesIndex++];
  1704. }
  1705. }
  1706. return data;
  1707. });
  1708. });
  1709. }
  1710. return accessor._data;
  1711. };
  1712. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  1713. var _this = this;
  1714. if (bufferView._babylonBuffer) {
  1715. return bufferView._babylonBuffer;
  1716. }
  1717. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  1718. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  1719. });
  1720. return bufferView._babylonBuffer;
  1721. };
  1722. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  1723. var _this = this;
  1724. if (accessor._babylonVertexBuffer) {
  1725. return accessor._babylonVertexBuffer;
  1726. }
  1727. if (accessor.sparse) {
  1728. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {
  1729. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);
  1730. });
  1731. }
  1732. else {
  1733. var bufferView_1 = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  1734. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {
  1735. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  1736. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  1737. });
  1738. }
  1739. return accessor._babylonVertexBuffer;
  1740. };
  1741. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  1742. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  1743. if (!babylonMaterial) {
  1744. babylonMaterial = this._createMaterial("__gltf_default", drawMode);
  1745. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  1746. babylonMaterial.metallic = 1;
  1747. babylonMaterial.roughness = 1;
  1748. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  1749. }
  1750. return babylonMaterial;
  1751. };
  1752. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  1753. var promises = new Array();
  1754. // Ensure metallic workflow
  1755. babylonMaterial.metallic = 1;
  1756. babylonMaterial.roughness = 1;
  1757. var properties = material.pbrMetallicRoughness;
  1758. if (properties) {
  1759. if (properties.baseColorFactor) {
  1760. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  1761. babylonMaterial.alpha = properties.baseColorFactor[3];
  1762. }
  1763. else {
  1764. babylonMaterial.albedoColor = BABYLON.Color3.White();
  1765. }
  1766. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  1767. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  1768. if (properties.baseColorTexture) {
  1769. promises.push(this._loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  1770. babylonMaterial.albedoTexture = texture;
  1771. }));
  1772. }
  1773. if (properties.metallicRoughnessTexture) {
  1774. promises.push(this._loadTextureInfoAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  1775. babylonMaterial.metallicTexture = texture;
  1776. }));
  1777. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  1778. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  1779. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  1780. }
  1781. }
  1782. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  1783. return Promise.all(promises).then(function () { });
  1784. };
  1785. GLTFLoader.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  1786. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, mesh, babylonMesh, babylonDrawMode, assign);
  1787. if (extensionPromise) {
  1788. return extensionPromise;
  1789. }
  1790. material._babylonData = material._babylonData || {};
  1791. var babylonData = material._babylonData[babylonDrawMode];
  1792. if (!babylonData) {
  1793. this._parent._logOpen(context + " " + (material.name || ""));
  1794. var name_4 = material.name || "material" + material._index;
  1795. var babylonMaterial = this._createMaterial(name_4, babylonDrawMode);
  1796. babylonData = {
  1797. material: babylonMaterial,
  1798. meshes: [],
  1799. loaded: this._loadMaterialPropertiesAsync(context, material, babylonMaterial)
  1800. };
  1801. material._babylonData[babylonDrawMode] = babylonData;
  1802. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  1803. this._parent._logClose();
  1804. }
  1805. babylonData.meshes.push(babylonMesh);
  1806. babylonMesh.onDisposeObservable.addOnce(function () {
  1807. var index = babylonData.meshes.indexOf(babylonMesh);
  1808. if (index !== -1) {
  1809. babylonData.meshes.splice(index, 1);
  1810. }
  1811. });
  1812. assign(babylonData.material);
  1813. return babylonData.loaded;
  1814. };
  1815. GLTFLoader.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  1816. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadMaterialPropertiesAsync(this, context, material, babylonMaterial);
  1817. if (extensionPromise) {
  1818. return extensionPromise;
  1819. }
  1820. var promises = new Array();
  1821. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  1822. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  1823. return Promise.all(promises).then(function () { });
  1824. };
  1825. GLTFLoader.prototype._createMaterial = function (name, drawMode) {
  1826. var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);
  1827. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  1828. babylonMaterial.fillMode = drawMode;
  1829. babylonMaterial.enableSpecularAntiAliasing = true;
  1830. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  1831. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  1832. return babylonMaterial;
  1833. };
  1834. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  1835. var promises = new Array();
  1836. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  1837. if (material.doubleSided) {
  1838. babylonMaterial.backFaceCulling = false;
  1839. babylonMaterial.twoSidedLighting = true;
  1840. }
  1841. if (material.normalTexture) {
  1842. promises.push(this._loadTextureInfoAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  1843. babylonMaterial.bumpTexture = texture;
  1844. }));
  1845. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  1846. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  1847. if (material.normalTexture.scale != undefined) {
  1848. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  1849. }
  1850. }
  1851. if (material.occlusionTexture) {
  1852. promises.push(this._loadTextureInfoAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  1853. babylonMaterial.ambientTexture = texture;
  1854. }));
  1855. babylonMaterial.useAmbientInGrayScale = true;
  1856. if (material.occlusionTexture.strength != undefined) {
  1857. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  1858. }
  1859. }
  1860. if (material.emissiveTexture) {
  1861. promises.push(this._loadTextureInfoAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  1862. babylonMaterial.emissiveTexture = texture;
  1863. }));
  1864. }
  1865. return Promise.all(promises).then(function () { });
  1866. };
  1867. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  1868. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  1869. switch (alphaMode) {
  1870. case "OPAQUE" /* OPAQUE */: {
  1871. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  1872. break;
  1873. }
  1874. case "MASK" /* MASK */: {
  1875. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  1876. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  1877. if (babylonMaterial.albedoTexture) {
  1878. babylonMaterial.albedoTexture.hasAlpha = true;
  1879. }
  1880. break;
  1881. }
  1882. case "BLEND" /* BLEND */: {
  1883. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  1884. if (babylonMaterial.albedoTexture) {
  1885. babylonMaterial.albedoTexture.hasAlpha = true;
  1886. babylonMaterial.useAlphaFromAlbedoTexture = true;
  1887. }
  1888. break;
  1889. }
  1890. default: {
  1891. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  1892. }
  1893. }
  1894. };
  1895. GLTFLoader.prototype._loadTextureInfoAsync = function (context, textureInfo, assign) {
  1896. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadTextureInfoAsync(this, context, textureInfo, assign);
  1897. if (extensionPromise) {
  1898. return extensionPromise;
  1899. }
  1900. this._parent._logOpen("" + context);
  1901. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  1902. var promise = this._loadTextureAsync("#/textures/" + textureInfo.index, texture, function (babylonTexture) {
  1903. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  1904. assign(babylonTexture);
  1905. });
  1906. this._parent._logClose();
  1907. return promise;
  1908. };
  1909. GLTFLoader.prototype._loadTextureAsync = function (context, texture, assign) {
  1910. var _this = this;
  1911. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadTextureAsync(this, context, texture, assign);
  1912. if (extensionPromise) {
  1913. return extensionPromise;
  1914. }
  1915. var promises = new Array();
  1916. this._parent._logOpen(context + " " + (texture.name || ""));
  1917. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  1918. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  1919. var deferred = new BABYLON.Deferred();
  1920. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  1921. if (!_this._disposed) {
  1922. deferred.resolve();
  1923. }
  1924. }, function (message, exception) {
  1925. if (!_this._disposed) {
  1926. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  1927. }
  1928. });
  1929. promises.push(deferred.promise);
  1930. babylonTexture.name = texture.name || "texture" + texture._index;
  1931. babylonTexture.wrapU = samplerData.wrapU;
  1932. babylonTexture.wrapV = samplerData.wrapV;
  1933. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  1934. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (data) {
  1935. var dataUrl = "data:" + _this._rootUrl + (image.uri || "image" + image._index);
  1936. babylonTexture.updateURL(dataUrl, new Blob([data], { type: image.mimeType }));
  1937. }));
  1938. assign(babylonTexture);
  1939. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  1940. this._parent._logClose();
  1941. return Promise.all(promises).then(function () { });
  1942. };
  1943. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  1944. if (!sampler._data) {
  1945. sampler._data = {
  1946. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  1947. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  1948. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  1949. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  1950. };
  1951. }
  1952. ;
  1953. return sampler._data;
  1954. };
  1955. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  1956. if (!image._data) {
  1957. this._parent._logOpen(context + " " + (image.name || ""));
  1958. if (image.uri) {
  1959. image._data = this._loadUriAsync(context, image.uri);
  1960. }
  1961. else {
  1962. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  1963. image._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  1964. }
  1965. this._parent._logClose();
  1966. }
  1967. return image._data;
  1968. };
  1969. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  1970. var _this = this;
  1971. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  1972. if (extensionPromise) {
  1973. return extensionPromise;
  1974. }
  1975. if (!GLTFLoader._ValidateUri(uri)) {
  1976. throw new Error(context + ": Uri '" + uri + "' is invalid");
  1977. }
  1978. if (BABYLON.Tools.IsBase64(uri)) {
  1979. var data = new Uint8Array(BABYLON.Tools.DecodeBase64(uri));
  1980. this._parent._log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)");
  1981. return Promise.resolve(data);
  1982. }
  1983. this._parent._log("Loading " + uri);
  1984. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  1985. return new Promise(function (resolve, reject) {
  1986. if (!_this._disposed) {
  1987. var request_1 = BABYLON.Tools.LoadFile(url, function (fileData) {
  1988. if (!_this._disposed) {
  1989. var data = new Uint8Array(fileData);
  1990. _this._parent._log("Loaded " + uri + " (" + data.length + " bytes)");
  1991. resolve(data);
  1992. }
  1993. }, function (event) {
  1994. if (!_this._disposed) {
  1995. if (request_1) {
  1996. request_1._lengthComputable = event.lengthComputable;
  1997. request_1._loaded = event.loaded;
  1998. request_1._total = event.total;
  1999. }
  2000. if (_this._state === BABYLON.GLTFLoaderState.LOADING) {
  2001. try {
  2002. _this._onProgress();
  2003. }
  2004. catch (e) {
  2005. reject(e);
  2006. }
  2007. }
  2008. }
  2009. }, _this._babylonScene.database, true, function (request, exception) {
  2010. if (!_this._disposed) {
  2011. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  2012. }
  2013. });
  2014. _this._requests.push(request_1);
  2015. }
  2016. });
  2017. });
  2018. };
  2019. GLTFLoader.prototype._onProgress = function () {
  2020. if (!this._progressCallback) {
  2021. return;
  2022. }
  2023. var lengthComputable = true;
  2024. var loaded = 0;
  2025. var total = 0;
  2026. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  2027. var request = _a[_i];
  2028. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  2029. return;
  2030. }
  2031. lengthComputable = lengthComputable && request._lengthComputable;
  2032. loaded += request._loaded;
  2033. total += request._total;
  2034. }
  2035. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  2036. };
  2037. GLTFLoader._GetProperty = function (context, array, index) {
  2038. if (!array || index == undefined || !array[index]) {
  2039. throw new Error(context + ": Failed to find index (" + index + ")");
  2040. }
  2041. return array[index];
  2042. };
  2043. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  2044. // Set defaults if undefined
  2045. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  2046. switch (mode) {
  2047. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  2048. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  2049. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2050. default:
  2051. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  2052. return BABYLON.Texture.WRAP_ADDRESSMODE;
  2053. }
  2054. };
  2055. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  2056. // Set defaults if undefined
  2057. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  2058. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  2059. if (magFilter === 9729 /* LINEAR */) {
  2060. switch (minFilter) {
  2061. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  2062. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  2063. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  2064. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  2065. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  2066. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  2067. default:
  2068. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  2069. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  2070. }
  2071. }
  2072. else {
  2073. if (magFilter !== 9728 /* NEAREST */) {
  2074. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  2075. }
  2076. switch (minFilter) {
  2077. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  2078. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  2079. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  2080. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  2081. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  2082. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  2083. default:
  2084. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  2085. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  2086. }
  2087. }
  2088. };
  2089. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  2090. var buffer = bufferView.buffer;
  2091. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  2092. try {
  2093. switch (componentType) {
  2094. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  2095. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  2096. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  2097. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  2098. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  2099. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  2100. default: throw new Error("Invalid component type " + componentType);
  2101. }
  2102. }
  2103. catch (e) {
  2104. throw new Error(context + ": " + e);
  2105. }
  2106. };
  2107. GLTFLoader._GetNumComponents = function (context, type) {
  2108. switch (type) {
  2109. case "SCALAR": return 1;
  2110. case "VEC2": return 2;
  2111. case "VEC3": return 3;
  2112. case "VEC4": return 4;
  2113. case "MAT2": return 4;
  2114. case "MAT3": return 9;
  2115. case "MAT4": return 16;
  2116. }
  2117. throw new Error(context + ": Invalid type (" + type + ")");
  2118. };
  2119. GLTFLoader._ValidateUri = function (uri) {
  2120. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  2121. };
  2122. GLTFLoader._GetDrawMode = function (context, mode) {
  2123. if (mode == undefined) {
  2124. mode = 4 /* TRIANGLES */;
  2125. }
  2126. switch (mode) {
  2127. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  2128. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  2129. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  2130. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  2131. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  2132. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  2133. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  2134. }
  2135. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  2136. };
  2137. GLTFLoader.prototype._compileMaterialsAsync = function () {
  2138. var _this = this;
  2139. this._parent._startPerformanceCounter("Compile materials");
  2140. var promises = new Array();
  2141. if (this._gltf.materials) {
  2142. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  2143. var material = _a[_i];
  2144. if (material._babylonData) {
  2145. for (var babylonDrawMode in material._babylonData) {
  2146. var babylonData = material._babylonData[babylonDrawMode];
  2147. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  2148. var babylonMesh = _c[_b];
  2149. // Ensure nonUniformScaling is set if necessary.
  2150. babylonMesh.computeWorldMatrix(true);
  2151. var babylonMaterial = babylonData.material;
  2152. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  2153. if (this._parent.useClipPlane) {
  2154. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  2155. }
  2156. }
  2157. }
  2158. }
  2159. }
  2160. }
  2161. return Promise.all(promises).then(function () {
  2162. _this._parent._endPerformanceCounter("Compile materials");
  2163. });
  2164. };
  2165. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  2166. var _this = this;
  2167. this._parent._startPerformanceCounter("Compile shadow generators");
  2168. var promises = new Array();
  2169. var lights = this._babylonScene.lights;
  2170. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  2171. var light = lights_1[_i];
  2172. var generator = light.getShadowGenerator();
  2173. if (generator) {
  2174. promises.push(generator.forceCompilationAsync());
  2175. }
  2176. }
  2177. return Promise.all(promises).then(function () {
  2178. _this._parent._endPerformanceCounter("Compile shadow generators");
  2179. });
  2180. };
  2181. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  2182. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  2183. var name_5 = _a[_i];
  2184. var extension = this._extensions[name_5];
  2185. if (extension.enabled) {
  2186. var promise = actionAsync(extension);
  2187. if (promise) {
  2188. return promise;
  2189. }
  2190. }
  2191. }
  2192. return null;
  2193. };
  2194. GLTFLoader.prototype._forEachExtensions = function (action) {
  2195. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  2196. var name_6 = _a[_i];
  2197. var extension = this._extensions[name_6];
  2198. if (extension.enabled) {
  2199. action(extension);
  2200. }
  2201. }
  2202. };
  2203. GLTFLoader._ExtensionNames = new Array();
  2204. GLTFLoader._ExtensionFactories = {};
  2205. return GLTFLoader;
  2206. }());
  2207. GLTF2.GLTFLoader = GLTFLoader;
  2208. BABYLON.GLTFFileLoader._CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  2209. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2210. })(BABYLON || (BABYLON = {}));
  2211. //# sourceMappingURL=babylon.glTFLoader.js.map
  2212. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2213. var BABYLON;
  2214. (function (BABYLON) {
  2215. var GLTF2;
  2216. (function (GLTF2) {
  2217. /**
  2218. * Abstract class that can be implemented to extend existing glTF loader behavior.
  2219. */
  2220. var GLTFLoaderExtension = /** @class */ (function () {
  2221. /**
  2222. * Creates new GLTFLoaderExtension
  2223. * @param loader defines the GLTFLoader to use
  2224. */
  2225. function GLTFLoaderExtension(loader) {
  2226. /**
  2227. * Gets or sets a boolean indicating if the extension is enabled
  2228. */
  2229. this.enabled = true;
  2230. this._loader = loader;
  2231. }
  2232. /**
  2233. * Release all resources
  2234. */
  2235. GLTFLoaderExtension.prototype.dispose = function () {
  2236. delete this._loader;
  2237. };
  2238. // #region Overridable Methods
  2239. /**
  2240. * Override this method to do work after the state changes to LOADING.
  2241. */
  2242. GLTFLoaderExtension.prototype._onLoading = function () { };
  2243. /**
  2244. * Override this method to do work after the state changes to READY.
  2245. */
  2246. GLTFLoaderExtension.prototype._onReady = function () { };
  2247. /**
  2248. * Override this method to modify the default behavior for loading scenes.
  2249. * @hidden
  2250. */
  2251. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  2252. /**
  2253. * Override this method to modify the default behavior for loading nodes.
  2254. * @hidden
  2255. */
  2256. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  2257. /**
  2258. * Override this method to modify the default behavior for loading mesh primitive vertex data.
  2259. * @hidden
  2260. */
  2261. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  2262. /**
  2263. * Override this method to modify the default behavior for loading materials.
  2264. * @hidden
  2265. */
  2266. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { return null; };
  2267. /**
  2268. * Override this method to modify the default behavior for loading material properties.
  2269. * @hidden
  2270. */
  2271. GLTFLoaderExtension.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) { return null; };
  2272. /**
  2273. * Override this method to modify the default behavior for loading texture infos.
  2274. * @hidden
  2275. */
  2276. GLTFLoaderExtension.prototype._loadTextureInfoAsync = function (context, textureInfo, assign) { return null; };
  2277. /**
  2278. * Override this method to modify the default behavior for loading textures.
  2279. * @hidden
  2280. */
  2281. GLTFLoaderExtension.prototype._loadTextureAsync = function (context, texture, assign) { return null; };
  2282. /**
  2283. * Override this method to modify the default behavior for loading uris.
  2284. * @hidden
  2285. */
  2286. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  2287. // #endregion
  2288. /**
  2289. * Helper method called by a loader extension to load an glTF extension.
  2290. * @hidden
  2291. */
  2292. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  2293. if (!property.extensions) {
  2294. return null;
  2295. }
  2296. var extensions = property.extensions;
  2297. var extension = extensions[this.name];
  2298. if (!extension) {
  2299. return null;
  2300. }
  2301. // Clear out the extension before executing the action to avoid infinite recursion.
  2302. delete extensions[this.name];
  2303. try {
  2304. return actionAsync(context + "/extensions/" + this.name, extension);
  2305. }
  2306. finally {
  2307. // Restore the extension after executing the action.
  2308. extensions[this.name] = extension;
  2309. }
  2310. };
  2311. /**
  2312. * Helper method called by the loader to allow extensions to override loading scenes.
  2313. * @hidden
  2314. */
  2315. GLTFLoaderExtension.prototype._loadExtrasValueAsync = function (context, property, actionAsync) {
  2316. if (!property.extras) {
  2317. return null;
  2318. }
  2319. var extras = property.extras;
  2320. var value = extras[this.name];
  2321. if (value === undefined) {
  2322. return null;
  2323. }
  2324. // Clear out the extras value before executing the action to avoid infinite recursion.
  2325. delete extras[this.name];
  2326. try {
  2327. return actionAsync(context + "/extras/" + this.name, value);
  2328. }
  2329. finally {
  2330. // Restore the extras value after executing the action.
  2331. extras[this.name] = value;
  2332. }
  2333. };
  2334. /**
  2335. * Helper method called by the loader after the state changes to LOADING.
  2336. * @hidden
  2337. */
  2338. GLTFLoaderExtension._OnLoading = function (loader) {
  2339. loader._forEachExtensions(function (extension) { return extension._onLoading(); });
  2340. };
  2341. /**
  2342. * Helper method called by the loader after the state changes to READY.
  2343. * @hidden
  2344. */
  2345. GLTFLoaderExtension._OnReady = function (loader) {
  2346. loader._forEachExtensions(function (extension) { return extension._onReady(); });
  2347. };
  2348. /**
  2349. * Helper method called by the loader to allow extensions to override loading scenes.
  2350. * @hidden
  2351. */
  2352. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  2353. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  2354. };
  2355. /**
  2356. * Helper method called by the loader to allow extensions to override loading nodes.
  2357. * @hidden
  2358. */
  2359. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  2360. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  2361. };
  2362. /**
  2363. * Helper method called by the loader to allow extensions to override loading mesh primitive vertex data.
  2364. * @hidden
  2365. */
  2366. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  2367. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  2368. };
  2369. /**
  2370. * Helper method called by the loader to allow extensions to override loading materials.
  2371. * @hidden
  2372. */
  2373. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  2374. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, assign); });
  2375. };
  2376. /**
  2377. * Helper method called by the loader to allow extensions to override loading material properties.
  2378. * @hidden
  2379. */
  2380. GLTFLoaderExtension._LoadMaterialPropertiesAsync = function (loader, context, material, babylonMaterial) {
  2381. return loader._applyExtensions(function (extension) { return extension._loadMaterialPropertiesAsync(context, material, babylonMaterial); });
  2382. };
  2383. /**
  2384. * Helper method called by the loader to allow extensions to override loading texture infos.
  2385. * @hidden
  2386. */
  2387. GLTFLoaderExtension._LoadTextureInfoAsync = function (loader, context, textureInfo, assign) {
  2388. return loader._applyExtensions(function (extension) { return extension._loadTextureInfoAsync(context, textureInfo, assign); });
  2389. };
  2390. /**
  2391. * Helper method called by the loader to allow extensions to override loading textures.
  2392. * @hidden
  2393. */
  2394. GLTFLoaderExtension._LoadTextureAsync = function (loader, context, texture, assign) {
  2395. return loader._applyExtensions(function (extension) { return extension._loadTextureAsync(context, texture, assign); });
  2396. };
  2397. /**
  2398. * Helper method called by the loader to allow extensions to override loading uris.
  2399. * @hidden
  2400. */
  2401. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  2402. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  2403. };
  2404. return GLTFLoaderExtension;
  2405. }());
  2406. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  2407. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2408. })(BABYLON || (BABYLON = {}));
  2409. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2410. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2411. var __extends = (this && this.__extends) || (function () {
  2412. var extendStatics = Object.setPrototypeOf ||
  2413. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2414. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2415. return function (d, b) {
  2416. extendStatics(d, b);
  2417. function __() { this.constructor = d; }
  2418. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2419. };
  2420. })();
  2421. var BABYLON;
  2422. (function (BABYLON) {
  2423. var GLTF2;
  2424. (function (GLTF2) {
  2425. var Extensions;
  2426. (function (Extensions) {
  2427. var NAME = "MSFT_lod";
  2428. /**
  2429. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  2430. */
  2431. var MSFT_lod = /** @class */ (function (_super) {
  2432. __extends(MSFT_lod, _super);
  2433. function MSFT_lod() {
  2434. var _this = _super !== null && _super.apply(this, arguments) || this;
  2435. _this.name = NAME;
  2436. /**
  2437. * Maximum number of LODs to load, starting from the lowest LOD.
  2438. */
  2439. _this.maxLODsToLoad = Number.MAX_VALUE;
  2440. /**
  2441. * Observable raised when all node LODs of one level are loaded.
  2442. * The event data is the index of the loaded LOD starting from zero.
  2443. * Dispose the loader to cancel the loading of the next level of LODs.
  2444. */
  2445. _this.onNodeLODsLoadedObservable = new BABYLON.Observable();
  2446. /**
  2447. * Observable raised when all material LODs of one level are loaded.
  2448. * The event data is the index of the loaded LOD starting from zero.
  2449. * Dispose the loader to cancel the loading of the next level of LODs.
  2450. */
  2451. _this.onMaterialLODsLoadedObservable = new BABYLON.Observable();
  2452. _this._nodeIndexLOD = null;
  2453. _this._nodeSignalLODs = new Array();
  2454. _this._nodePromiseLODs = new Array();
  2455. _this._materialIndexLOD = null;
  2456. _this._materialSignalLODs = new Array();
  2457. _this._materialPromiseLODs = new Array();
  2458. return _this;
  2459. }
  2460. MSFT_lod.prototype.dispose = function () {
  2461. _super.prototype.dispose.call(this);
  2462. this._nodeIndexLOD = null;
  2463. this._nodeSignalLODs.length = 0;
  2464. this._nodePromiseLODs.length = 0;
  2465. this._materialIndexLOD = null;
  2466. this._materialSignalLODs.length = 0;
  2467. this._materialPromiseLODs.length = 0;
  2468. this.onMaterialLODsLoadedObservable.clear();
  2469. this.onNodeLODsLoadedObservable.clear();
  2470. };
  2471. MSFT_lod.prototype._onReady = function () {
  2472. var _this = this;
  2473. var _loop_1 = function (indexLOD) {
  2474. var promise = Promise.all(this_1._nodePromiseLODs[indexLOD]).then(function () {
  2475. if (indexLOD !== 0) {
  2476. _this._loader._parent._endPerformanceCounter("Node LOD " + indexLOD);
  2477. }
  2478. _this._loader._parent._log("Loaded node LOD " + indexLOD);
  2479. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  2480. if (indexLOD !== _this._nodePromiseLODs.length - 1) {
  2481. _this._loader._parent._startPerformanceCounter("Node LOD " + (indexLOD + 1));
  2482. if (_this._nodeSignalLODs[indexLOD]) {
  2483. _this._nodeSignalLODs[indexLOD].resolve();
  2484. }
  2485. }
  2486. });
  2487. this_1._loader._completePromises.push(promise);
  2488. };
  2489. var this_1 = this;
  2490. for (var indexLOD = 0; indexLOD < this._nodePromiseLODs.length; indexLOD++) {
  2491. _loop_1(indexLOD);
  2492. }
  2493. var _loop_2 = function (indexLOD) {
  2494. var promise = Promise.all(this_2._materialPromiseLODs[indexLOD]).then(function () {
  2495. if (indexLOD !== 0) {
  2496. _this._loader._parent._endPerformanceCounter("Material LOD " + indexLOD);
  2497. }
  2498. _this._loader._parent._log("Loaded material LOD " + indexLOD);
  2499. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  2500. if (indexLOD !== _this._materialPromiseLODs.length - 1) {
  2501. _this._loader._parent._startPerformanceCounter("Material LOD " + (indexLOD + 1));
  2502. if (_this._materialSignalLODs[indexLOD]) {
  2503. _this._materialSignalLODs[indexLOD].resolve();
  2504. }
  2505. }
  2506. });
  2507. this_2._loader._completePromises.push(promise);
  2508. };
  2509. var this_2 = this;
  2510. for (var indexLOD = 0; indexLOD < this._materialPromiseLODs.length; indexLOD++) {
  2511. _loop_2(indexLOD);
  2512. }
  2513. };
  2514. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  2515. var _this = this;
  2516. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  2517. var firstPromise;
  2518. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  2519. _this._loader._parent._logOpen("" + extensionContext);
  2520. var _loop_3 = function (indexLOD) {
  2521. var nodeLOD = nodeLODs[indexLOD];
  2522. if (indexLOD !== 0) {
  2523. _this._nodeIndexLOD = indexLOD;
  2524. _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new BABYLON.Deferred();
  2525. }
  2526. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  2527. if (indexLOD !== 0) {
  2528. var previousNodeLOD = nodeLODs[indexLOD - 1];
  2529. if (previousNodeLOD._babylonMesh) {
  2530. previousNodeLOD._babylonMesh.dispose();
  2531. delete previousNodeLOD._babylonMesh;
  2532. _this._disposeUnusedMaterials();
  2533. }
  2534. }
  2535. });
  2536. if (indexLOD === 0) {
  2537. firstPromise = promise;
  2538. }
  2539. else {
  2540. _this._nodeIndexLOD = null;
  2541. }
  2542. _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || [];
  2543. _this._nodePromiseLODs[indexLOD].push(promise);
  2544. };
  2545. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  2546. _loop_3(indexLOD);
  2547. }
  2548. _this._loader._parent._logClose();
  2549. return firstPromise;
  2550. });
  2551. };
  2552. MSFT_lod.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  2553. var _this = this;
  2554. // Don't load material LODs if already loading a node LOD.
  2555. if (this._nodeIndexLOD) {
  2556. return null;
  2557. }
  2558. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  2559. var firstPromise;
  2560. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  2561. _this._loader._parent._logOpen("" + extensionContext);
  2562. var _loop_4 = function (indexLOD) {
  2563. var materialLOD = materialLODs[indexLOD];
  2564. if (indexLOD !== 0) {
  2565. _this._materialIndexLOD = indexLOD;
  2566. }
  2567. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, mesh, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  2568. if (indexLOD !== 0) {
  2569. var babylonDataLOD = materialLOD._babylonData;
  2570. assign(babylonDataLOD[babylonDrawMode].material);
  2571. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  2572. if (previousBabylonDataLOD[babylonDrawMode]) {
  2573. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  2574. delete previousBabylonDataLOD[babylonDrawMode];
  2575. }
  2576. }
  2577. });
  2578. if (indexLOD === 0) {
  2579. firstPromise = promise;
  2580. }
  2581. else {
  2582. _this._materialIndexLOD = null;
  2583. }
  2584. _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || [];
  2585. _this._materialPromiseLODs[indexLOD].push(promise);
  2586. };
  2587. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  2588. _loop_4(indexLOD);
  2589. }
  2590. _this._loader._parent._logClose();
  2591. return firstPromise;
  2592. });
  2593. };
  2594. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  2595. var _this = this;
  2596. // Defer the loading of uris if loading a material or node LOD.
  2597. if (this._materialIndexLOD !== null) {
  2598. this._loader._parent._log("deferred");
  2599. var previousIndexLOD = this._materialIndexLOD - 1;
  2600. this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  2601. return this._materialSignalLODs[previousIndexLOD].promise.then(function () {
  2602. return _this._loader._loadUriAsync(context, uri);
  2603. });
  2604. }
  2605. else if (this._nodeIndexLOD !== null) {
  2606. this._loader._parent._log("deferred");
  2607. var previousIndexLOD = this._nodeIndexLOD - 1;
  2608. this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  2609. return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () {
  2610. return _this._loader._loadUriAsync(context, uri);
  2611. });
  2612. }
  2613. return null;
  2614. };
  2615. /**
  2616. * Gets an array of LOD properties from lowest to highest.
  2617. */
  2618. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  2619. if (this.maxLODsToLoad <= 0) {
  2620. throw new Error("maxLODsToLoad must be greater than zero");
  2621. }
  2622. var properties = new Array();
  2623. for (var i = ids.length - 1; i >= 0; i--) {
  2624. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  2625. if (properties.length === this.maxLODsToLoad) {
  2626. return properties;
  2627. }
  2628. }
  2629. properties.push(property);
  2630. return properties;
  2631. };
  2632. MSFT_lod.prototype._disposeUnusedMaterials = function () {
  2633. var materials = this._loader._gltf.materials;
  2634. if (materials) {
  2635. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  2636. var material = materials_1[_i];
  2637. if (material._babylonData) {
  2638. for (var drawMode in material._babylonData) {
  2639. var babylonData = material._babylonData[drawMode];
  2640. if (babylonData.meshes.length === 0) {
  2641. babylonData.material.dispose(false, true);
  2642. delete material._babylonData[drawMode];
  2643. }
  2644. }
  2645. }
  2646. }
  2647. }
  2648. };
  2649. return MSFT_lod;
  2650. }(GLTF2.GLTFLoaderExtension));
  2651. Extensions.MSFT_lod = MSFT_lod;
  2652. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  2653. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2654. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2655. })(BABYLON || (BABYLON = {}));
  2656. //# sourceMappingURL=MSFT_lod.js.map
  2657. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2658. var __extends = (this && this.__extends) || (function () {
  2659. var extendStatics = Object.setPrototypeOf ||
  2660. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2661. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2662. return function (d, b) {
  2663. extendStatics(d, b);
  2664. function __() { this.constructor = d; }
  2665. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2666. };
  2667. })();
  2668. var BABYLON;
  2669. (function (BABYLON) {
  2670. var GLTF2;
  2671. (function (GLTF2) {
  2672. var Extensions;
  2673. (function (Extensions) {
  2674. var NAME = "MSFT_minecraftMesh";
  2675. /** @hidden */
  2676. var MSFT_minecraftMesh = /** @class */ (function (_super) {
  2677. __extends(MSFT_minecraftMesh, _super);
  2678. function MSFT_minecraftMesh() {
  2679. var _this = _super !== null && _super.apply(this, arguments) || this;
  2680. _this.name = NAME;
  2681. return _this;
  2682. }
  2683. MSFT_minecraftMesh.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  2684. var _this = this;
  2685. return this._loadExtrasValueAsync(context, mesh, function (extensionContext, value) {
  2686. if (value) {
  2687. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  2688. if (babylonMaterial.needAlphaBlending()) {
  2689. babylonMaterial.forceDepthWrite = true;
  2690. babylonMaterial.separateCullingPass = true;
  2691. }
  2692. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  2693. babylonMaterial.twoSidedLighting = true;
  2694. assign(babylonMaterial);
  2695. });
  2696. }
  2697. return null;
  2698. });
  2699. };
  2700. return MSFT_minecraftMesh;
  2701. }(GLTF2.GLTFLoaderExtension));
  2702. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  2703. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  2704. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2705. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2706. })(BABYLON || (BABYLON = {}));
  2707. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  2708. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2709. var __extends = (this && this.__extends) || (function () {
  2710. var extendStatics = Object.setPrototypeOf ||
  2711. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2712. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2713. return function (d, b) {
  2714. extendStatics(d, b);
  2715. function __() { this.constructor = d; }
  2716. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2717. };
  2718. })();
  2719. var BABYLON;
  2720. (function (BABYLON) {
  2721. var GLTF2;
  2722. (function (GLTF2) {
  2723. var Extensions;
  2724. (function (Extensions) {
  2725. var NAME = "MSFT_sRGBFactors";
  2726. /** @hidden */
  2727. var MSFT_sRGBFactors = /** @class */ (function (_super) {
  2728. __extends(MSFT_sRGBFactors, _super);
  2729. function MSFT_sRGBFactors() {
  2730. var _this = _super !== null && _super.apply(this, arguments) || this;
  2731. _this.name = NAME;
  2732. return _this;
  2733. }
  2734. MSFT_sRGBFactors.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  2735. var _this = this;
  2736. return this._loadExtrasValueAsync(context, material, function (extensionContext, value) {
  2737. if (value) {
  2738. var promise = _this._loader._loadMaterialPropertiesAsync(context, material, babylonMaterial);
  2739. _this._convertColorsToLinear(babylonMaterial);
  2740. return promise;
  2741. }
  2742. return null;
  2743. });
  2744. };
  2745. MSFT_sRGBFactors.prototype._convertColorsToLinear = function (babylonMaterial) {
  2746. if (!babylonMaterial.albedoTexture) {
  2747. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  2748. }
  2749. if (!babylonMaterial.reflectivityTexture) {
  2750. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  2751. }
  2752. };
  2753. return MSFT_sRGBFactors;
  2754. }(GLTF2.GLTFLoaderExtension));
  2755. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  2756. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  2757. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2758. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2759. })(BABYLON || (BABYLON = {}));
  2760. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  2761. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2762. var __extends = (this && this.__extends) || (function () {
  2763. var extendStatics = Object.setPrototypeOf ||
  2764. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2765. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2766. return function (d, b) {
  2767. extendStatics(d, b);
  2768. function __() { this.constructor = d; }
  2769. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2770. };
  2771. })();
  2772. var BABYLON;
  2773. (function (BABYLON) {
  2774. var GLTF2;
  2775. (function (GLTF2) {
  2776. var Extensions;
  2777. (function (Extensions) {
  2778. var NAME = "KHR_draco_mesh_compression";
  2779. /**
  2780. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  2781. */
  2782. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  2783. __extends(KHR_draco_mesh_compression, _super);
  2784. function KHR_draco_mesh_compression(loader) {
  2785. var _this = _super.call(this, loader) || this;
  2786. _this.name = NAME;
  2787. _this._dracoCompression = null;
  2788. // Disable extension if decoder is not available.
  2789. if (!BABYLON.DracoCompression.DecoderAvailable) {
  2790. _this.enabled = false;
  2791. }
  2792. return _this;
  2793. }
  2794. KHR_draco_mesh_compression.prototype.dispose = function () {
  2795. if (this._dracoCompression) {
  2796. this._dracoCompression.dispose();
  2797. }
  2798. _super.prototype.dispose.call(this);
  2799. };
  2800. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  2801. var _this = this;
  2802. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  2803. if (primitive.mode != undefined) {
  2804. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  2805. primitive.mode !== 4 /* TRIANGLES */) {
  2806. throw new Error(context + ": Unsupported mode " + primitive.mode);
  2807. }
  2808. // TODO: handle triangle strips
  2809. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  2810. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  2811. }
  2812. }
  2813. var attributes = {};
  2814. var loadAttribute = function (name, kind) {
  2815. var uniqueId = extension.attributes[name];
  2816. if (uniqueId == undefined) {
  2817. return;
  2818. }
  2819. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  2820. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  2821. babylonMesh._delayInfo.push(kind);
  2822. }
  2823. attributes[kind] = uniqueId;
  2824. };
  2825. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  2826. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  2827. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  2828. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  2829. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  2830. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  2831. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  2832. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  2833. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  2834. if (!bufferView._dracoBabylonGeometry) {
  2835. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  2836. if (!_this._dracoCompression) {
  2837. _this._dracoCompression = new BABYLON.DracoCompression();
  2838. }
  2839. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  2840. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  2841. babylonVertexData.applyToGeometry(babylonGeometry);
  2842. return babylonGeometry;
  2843. }).catch(function (error) {
  2844. throw new Error(context + ": " + error.message);
  2845. });
  2846. });
  2847. }
  2848. return bufferView._dracoBabylonGeometry;
  2849. });
  2850. };
  2851. return KHR_draco_mesh_compression;
  2852. }(GLTF2.GLTFLoaderExtension));
  2853. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  2854. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  2855. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2856. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2857. })(BABYLON || (BABYLON = {}));
  2858. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  2859. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2860. var __extends = (this && this.__extends) || (function () {
  2861. var extendStatics = Object.setPrototypeOf ||
  2862. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2863. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2864. return function (d, b) {
  2865. extendStatics(d, b);
  2866. function __() { this.constructor = d; }
  2867. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2868. };
  2869. })();
  2870. var BABYLON;
  2871. (function (BABYLON) {
  2872. var GLTF2;
  2873. (function (GLTF2) {
  2874. var Extensions;
  2875. (function (Extensions) {
  2876. var NAME = "KHR_materials_pbrSpecularGlossiness";
  2877. /**
  2878. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  2879. */
  2880. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  2881. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  2882. function KHR_materials_pbrSpecularGlossiness() {
  2883. var _this = _super !== null && _super.apply(this, arguments) || this;
  2884. _this.name = NAME;
  2885. return _this;
  2886. }
  2887. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  2888. var _this = this;
  2889. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  2890. var promises = new Array();
  2891. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  2892. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  2893. return Promise.all(promises).then(function () { });
  2894. });
  2895. };
  2896. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  2897. var promises = new Array();
  2898. if (properties.diffuseFactor) {
  2899. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  2900. babylonMaterial.alpha = properties.diffuseFactor[3];
  2901. }
  2902. else {
  2903. babylonMaterial.albedoColor = BABYLON.Color3.White();
  2904. }
  2905. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  2906. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  2907. if (properties.diffuseTexture) {
  2908. promises.push(this._loader._loadTextureInfoAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  2909. babylonMaterial.albedoTexture = texture;
  2910. }));
  2911. }
  2912. if (properties.specularGlossinessTexture) {
  2913. promises.push(this._loader._loadTextureInfoAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  2914. babylonMaterial.reflectivityTexture = texture;
  2915. }));
  2916. babylonMaterial.reflectivityTexture.hasAlpha = true;
  2917. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  2918. }
  2919. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  2920. return Promise.all(promises).then(function () { });
  2921. };
  2922. return KHR_materials_pbrSpecularGlossiness;
  2923. }(GLTF2.GLTFLoaderExtension));
  2924. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  2925. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  2926. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2927. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2928. })(BABYLON || (BABYLON = {}));
  2929. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  2930. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2931. var __extends = (this && this.__extends) || (function () {
  2932. var extendStatics = Object.setPrototypeOf ||
  2933. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2934. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2935. return function (d, b) {
  2936. extendStatics(d, b);
  2937. function __() { this.constructor = d; }
  2938. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2939. };
  2940. })();
  2941. var BABYLON;
  2942. (function (BABYLON) {
  2943. var GLTF2;
  2944. (function (GLTF2) {
  2945. var Extensions;
  2946. (function (Extensions) {
  2947. var NAME = "KHR_materials_unlit";
  2948. /**
  2949. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  2950. */
  2951. var KHR_materials_unlit = /** @class */ (function (_super) {
  2952. __extends(KHR_materials_unlit, _super);
  2953. function KHR_materials_unlit() {
  2954. var _this = _super !== null && _super.apply(this, arguments) || this;
  2955. _this.name = NAME;
  2956. return _this;
  2957. }
  2958. KHR_materials_unlit.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  2959. var _this = this;
  2960. return this._loadExtensionAsync(context, material, function () {
  2961. return _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  2962. });
  2963. };
  2964. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  2965. var promises = new Array();
  2966. babylonMaterial.unlit = true;
  2967. // Ensure metallic workflow
  2968. babylonMaterial.metallic = 1;
  2969. babylonMaterial.roughness = 1;
  2970. var properties = material.pbrMetallicRoughness;
  2971. if (properties) {
  2972. if (properties.baseColorFactor) {
  2973. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  2974. babylonMaterial.alpha = properties.baseColorFactor[3];
  2975. }
  2976. else {
  2977. babylonMaterial.albedoColor = BABYLON.Color3.White();
  2978. }
  2979. if (properties.baseColorTexture) {
  2980. promises.push(this._loader._loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  2981. babylonMaterial.albedoTexture = texture;
  2982. }));
  2983. }
  2984. }
  2985. if (material.doubleSided) {
  2986. babylonMaterial.backFaceCulling = false;
  2987. babylonMaterial.twoSidedLighting = true;
  2988. }
  2989. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  2990. return Promise.all(promises).then(function () { });
  2991. };
  2992. return KHR_materials_unlit;
  2993. }(GLTF2.GLTFLoaderExtension));
  2994. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  2995. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  2996. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  2997. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2998. })(BABYLON || (BABYLON = {}));
  2999. //# sourceMappingURL=KHR_materials_unlit.js.map
  3000. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3001. var __extends = (this && this.__extends) || (function () {
  3002. var extendStatics = Object.setPrototypeOf ||
  3003. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  3004. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  3005. return function (d, b) {
  3006. extendStatics(d, b);
  3007. function __() { this.constructor = d; }
  3008. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3009. };
  3010. })();
  3011. var BABYLON;
  3012. (function (BABYLON) {
  3013. var GLTF2;
  3014. (function (GLTF2) {
  3015. var Extensions;
  3016. (function (Extensions) {
  3017. var NAME = "KHR_lights";
  3018. var LightType;
  3019. (function (LightType) {
  3020. LightType["AMBIENT"] = "ambient";
  3021. LightType["DIRECTIONAL"] = "directional";
  3022. LightType["POINT"] = "point";
  3023. LightType["SPOT"] = "spot";
  3024. })(LightType || (LightType = {}));
  3025. /**
  3026. * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)
  3027. */
  3028. var KHR_lights = /** @class */ (function (_super) {
  3029. __extends(KHR_lights, _super);
  3030. function KHR_lights() {
  3031. var _this = _super !== null && _super.apply(this, arguments) || this;
  3032. _this.name = NAME;
  3033. return _this;
  3034. }
  3035. KHR_lights.prototype._onLoading = function () {
  3036. var extensions = this._loader._gltf.extensions;
  3037. if (extensions && extensions[this.name]) {
  3038. var extension = extensions[this.name];
  3039. this._lights = extension.lights;
  3040. }
  3041. };
  3042. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  3043. var _this = this;
  3044. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  3045. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  3046. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  3047. if (light.type !== LightType.AMBIENT) {
  3048. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  3049. }
  3050. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  3051. return promise;
  3052. });
  3053. };
  3054. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  3055. var _this = this;
  3056. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  3057. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  3058. var babylonLight;
  3059. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  3060. var name = node._babylonMesh.name;
  3061. switch (light.type) {
  3062. case LightType.AMBIENT: {
  3063. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  3064. }
  3065. case LightType.DIRECTIONAL: {
  3066. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  3067. break;
  3068. }
  3069. case LightType.POINT: {
  3070. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  3071. break;
  3072. }
  3073. case LightType.SPOT: {
  3074. // TODO: support inner and outer cone angles
  3075. //const innerConeAngle = spotLight.innerConeAngle || 0;
  3076. var outerConeAngle = light.spot && light.spot.outerConeAngle || Math.PI / 4;
  3077. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  3078. break;
  3079. }
  3080. default: {
  3081. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  3082. }
  3083. }
  3084. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  3085. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  3086. babylonLight.parent = node._babylonMesh;
  3087. return promise;
  3088. });
  3089. };
  3090. return KHR_lights;
  3091. }(GLTF2.GLTFLoaderExtension));
  3092. Extensions.KHR_lights = KHR_lights;
  3093. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  3094. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  3095. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3096. })(BABYLON || (BABYLON = {}));
  3097. //# sourceMappingURL=KHR_lights.js.map
  3098. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3099. var __extends = (this && this.__extends) || (function () {
  3100. var extendStatics = Object.setPrototypeOf ||
  3101. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  3102. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  3103. return function (d, b) {
  3104. extendStatics(d, b);
  3105. function __() { this.constructor = d; }
  3106. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3107. };
  3108. })();
  3109. var BABYLON;
  3110. (function (BABYLON) {
  3111. var GLTF2;
  3112. (function (GLTF2) {
  3113. var Extensions;
  3114. (function (Extensions) {
  3115. var NAME = "KHR_texture_transform";
  3116. /**
  3117. * [Specification](https://github.com/AltspaceVR/glTF/blob/avr-sampler-offset-tile/extensions/2.0/Khronos/KHR_texture_transform/README.md) (Experimental)
  3118. */
  3119. var KHR_texture_transform = /** @class */ (function (_super) {
  3120. __extends(KHR_texture_transform, _super);
  3121. function KHR_texture_transform() {
  3122. var _this = _super !== null && _super.apply(this, arguments) || this;
  3123. _this.name = NAME;
  3124. return _this;
  3125. }
  3126. KHR_texture_transform.prototype._loadTextureInfoAsync = function (context, textureInfo, assign) {
  3127. var _this = this;
  3128. return this._loadExtensionAsync(context, textureInfo, function (extensionContext, extension) {
  3129. return _this._loader._loadTextureInfoAsync(context, textureInfo, function (babylonTexture) {
  3130. if (extension.offset) {
  3131. babylonTexture.uOffset = extension.offset[0];
  3132. babylonTexture.vOffset = extension.offset[1];
  3133. }
  3134. // Always rotate around the origin.
  3135. babylonTexture.uRotationCenter = 0;
  3136. babylonTexture.vRotationCenter = 0;
  3137. if (extension.rotation) {
  3138. babylonTexture.wAng = -extension.rotation;
  3139. }
  3140. if (extension.scale) {
  3141. babylonTexture.uScale = extension.scale[0];
  3142. babylonTexture.vScale = extension.scale[1];
  3143. }
  3144. if (extension.texCoord != undefined) {
  3145. babylonTexture.coordinatesIndex = extension.texCoord;
  3146. }
  3147. assign(babylonTexture);
  3148. });
  3149. });
  3150. };
  3151. return KHR_texture_transform;
  3152. }(GLTF2.GLTFLoaderExtension));
  3153. Extensions.KHR_texture_transform = KHR_texture_transform;
  3154. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_texture_transform(loader); });
  3155. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  3156. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3157. })(BABYLON || (BABYLON = {}));
  3158. //# sourceMappingURL=KHR_texture_transform.js.map
  3159. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  3160. var __extends = (this && this.__extends) || (function () {
  3161. var extendStatics = Object.setPrototypeOf ||
  3162. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  3163. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  3164. return function (d, b) {
  3165. extendStatics(d, b);
  3166. function __() { this.constructor = d; }
  3167. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3168. };
  3169. })();
  3170. var BABYLON;
  3171. (function (BABYLON) {
  3172. var GLTF2;
  3173. (function (GLTF2) {
  3174. var Extensions;
  3175. (function (Extensions) {
  3176. var NAME = "EXT_lights_imageBased";
  3177. /**
  3178. * [Specification](TODO) (Experimental)
  3179. */
  3180. var EXT_lights_imageBased = /** @class */ (function (_super) {
  3181. __extends(EXT_lights_imageBased, _super);
  3182. function EXT_lights_imageBased() {
  3183. var _this = _super !== null && _super.apply(this, arguments) || this;
  3184. _this.name = NAME;
  3185. return _this;
  3186. }
  3187. EXT_lights_imageBased.prototype._onLoading = function () {
  3188. var extensions = this._loader._gltf.extensions;
  3189. if (extensions && extensions[this.name]) {
  3190. var extension = extensions[this.name];
  3191. this._lights = extension.lights;
  3192. }
  3193. };
  3194. EXT_lights_imageBased.prototype._loadSceneAsync = function (context, scene) {
  3195. var _this = this;
  3196. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  3197. var promises = new Array();
  3198. promises.push(_this._loader._loadSceneAsync(context, scene));
  3199. _this._loader._parent._logOpen("" + extensionContext);
  3200. var light = GLTF2.GLTFLoader._GetProperty(extensionContext + "/light", _this._lights, extension.light);
  3201. promises.push(_this._loadLightAsync("#/extensions/" + _this.name + "/lights/" + extension.light, light).then(function (texture) {
  3202. _this._loader._babylonScene.environmentTexture = texture;
  3203. }));
  3204. _this._loader._parent._logClose();
  3205. return Promise.all(promises).then(function () { });
  3206. });
  3207. };
  3208. EXT_lights_imageBased.prototype._loadLightAsync = function (context, light) {
  3209. var _this = this;
  3210. if (!light._loaded) {
  3211. var promises = new Array();
  3212. this._loader._parent._logOpen("" + context);
  3213. var imageData_1 = new Array(light.specularImages.length);
  3214. var _loop_1 = function (mipmap) {
  3215. var faces = light.specularImages[mipmap];
  3216. imageData_1[mipmap] = new Array(faces.length);
  3217. var _loop_2 = function (face) {
  3218. var specularImageContext = context + "/specularImages/" + mipmap + "/" + face;
  3219. this_1._loader._parent._logOpen("" + specularImageContext);
  3220. var index = faces[face];
  3221. var image = GLTF2.GLTFLoader._GetProperty(specularImageContext, this_1._loader._gltf.images, index);
  3222. promises.push(this_1._loader._loadImageAsync("#/images/" + index, image).then(function (data) {
  3223. imageData_1[mipmap][face] = data;
  3224. }));
  3225. this_1._loader._parent._logClose();
  3226. };
  3227. for (var face = 0; face < faces.length; face++) {
  3228. _loop_2(face);
  3229. }
  3230. };
  3231. var this_1 = this;
  3232. for (var mipmap = 0; mipmap < light.specularImages.length; mipmap++) {
  3233. _loop_1(mipmap);
  3234. }
  3235. this._loader._parent._logClose();
  3236. light._loaded = Promise.all(promises).then(function () {
  3237. var babylonTexture = new BABYLON.RawCubeTexture(_this._loader._babylonScene, null, light.specularImageSize);
  3238. light._babylonTexture = babylonTexture;
  3239. if (light.intensity != undefined) {
  3240. babylonTexture.level = light.intensity;
  3241. }
  3242. if (light.rotation) {
  3243. var rotation = BABYLON.Quaternion.FromArray(light.rotation);
  3244. // Invert the rotation so that positive rotation is counter-clockwise.
  3245. if (!_this._loader._babylonScene.useRightHandedSystem) {
  3246. rotation = BABYLON.Quaternion.Inverse(rotation);
  3247. }
  3248. BABYLON.Matrix.FromQuaternionToRef(rotation, babylonTexture.getReflectionTextureMatrix());
  3249. }
  3250. var sphericalHarmonics = BABYLON.SphericalHarmonics.FromArray(light.irradianceCoefficients);
  3251. sphericalHarmonics.scale(light.intensity);
  3252. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  3253. var sphericalPolynomial = BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  3254. // Compute the lod generation scale to fit exactly to the number of levels available.
  3255. var lodGenerationScale = (imageData_1.length - 1) / BABYLON.Scalar.Log2(light.specularImageSize);
  3256. return babylonTexture.updateRGBDAsync(imageData_1, sphericalPolynomial, lodGenerationScale);
  3257. });
  3258. }
  3259. return light._loaded.then(function () {
  3260. return light._babylonTexture;
  3261. });
  3262. };
  3263. return EXT_lights_imageBased;
  3264. }(GLTF2.GLTFLoaderExtension));
  3265. Extensions.EXT_lights_imageBased = EXT_lights_imageBased;
  3266. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new EXT_lights_imageBased(loader); });
  3267. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  3268. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3269. })(BABYLON || (BABYLON = {}));
  3270. //# sourceMappingURL=EXT_lights_imageBased.js.map