babylon.glTF2FileLoader.js 199 KB

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