babylon.glTF2FileLoader.js 203 KB

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