babylon.glTFFileLoader.js 223 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. var GLTFLoaderCoordinateSystemMode;
  5. (function (GLTFLoaderCoordinateSystemMode) {
  6. /**
  7. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  8. */
  9. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  10. /**
  11. * Sets the useRightHandedSystem flag on the scene.
  12. */
  13. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  14. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  15. var GLTFLoaderAnimationStartMode;
  16. (function (GLTFLoaderAnimationStartMode) {
  17. /**
  18. * No animation will start.
  19. */
  20. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  21. /**
  22. * The first animation will start.
  23. */
  24. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  25. /**
  26. * All animations will start.
  27. */
  28. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  29. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  30. var GLTFLoaderState;
  31. (function (GLTFLoaderState) {
  32. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  33. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  34. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  35. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  36. var GLTFFileLoader = /** @class */ (function () {
  37. function GLTFFileLoader() {
  38. // #region Common options
  39. /**
  40. * Raised when the asset has been parsed.
  41. * The data.json property stores the glTF JSON.
  42. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  43. */
  44. this.onParsedObservable = new BABYLON.Observable();
  45. // #endregion
  46. // #region V2 options
  47. /**
  48. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  49. */
  50. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  51. /**
  52. * The animation start mode (NONE, FIRST, ALL).
  53. */
  54. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  55. /**
  56. * Set to true to compile materials before raising the success callback.
  57. */
  58. this.compileMaterials = false;
  59. /**
  60. * Set to true to also compile materials with clip planes.
  61. */
  62. this.useClipPlane = false;
  63. /**
  64. * Set to true to compile shadow generators before raising the success callback.
  65. */
  66. this.compileShadowGenerators = false;
  67. /**
  68. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  69. */
  70. this.onMeshLoadedObservable = new BABYLON.Observable();
  71. /**
  72. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  73. */
  74. this.onTextureLoadedObservable = new BABYLON.Observable();
  75. /**
  76. * Raised when the loader creates a material after parsing the glTF properties of the material.
  77. */
  78. this.onMaterialLoadedObservable = new BABYLON.Observable();
  79. /**
  80. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  81. * For assets with LODs, raised when all of the LODs are complete.
  82. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  83. */
  84. this.onCompleteObservable = new BABYLON.Observable();
  85. /**
  86. * Raised when the loader is disposed.
  87. */
  88. this.onDisposeObservable = new BABYLON.Observable();
  89. /**
  90. * Raised after a loader extension is created.
  91. * Set additional options for a loader extension in this event.
  92. */
  93. this.onExtensionLoadedObservable = new BABYLON.Observable();
  94. // #endregion
  95. this._loader = null;
  96. this.name = "gltf";
  97. this.extensions = {
  98. ".gltf": { isBinary: false },
  99. ".glb": { isBinary: true }
  100. };
  101. }
  102. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  103. set: function (callback) {
  104. if (this._onParsedObserver) {
  105. this.onParsedObservable.remove(this._onParsedObserver);
  106. }
  107. this._onParsedObserver = this.onParsedObservable.add(callback);
  108. },
  109. enumerable: true,
  110. configurable: true
  111. });
  112. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  113. set: function (callback) {
  114. if (this._onMeshLoadedObserver) {
  115. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  116. }
  117. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  118. },
  119. enumerable: true,
  120. configurable: true
  121. });
  122. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  123. set: function (callback) {
  124. if (this._onTextureLoadedObserver) {
  125. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  126. }
  127. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  128. },
  129. enumerable: true,
  130. configurable: true
  131. });
  132. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  133. set: function (callback) {
  134. if (this._onMaterialLoadedObserver) {
  135. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  136. }
  137. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  138. },
  139. enumerable: true,
  140. configurable: true
  141. });
  142. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  143. set: function (callback) {
  144. if (this._onCompleteObserver) {
  145. this.onCompleteObservable.remove(this._onCompleteObserver);
  146. }
  147. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  148. },
  149. enumerable: true,
  150. configurable: true
  151. });
  152. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  153. set: function (callback) {
  154. if (this._onDisposeObserver) {
  155. this.onDisposeObservable.remove(this._onDisposeObserver);
  156. }
  157. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  158. },
  159. enumerable: true,
  160. configurable: true
  161. });
  162. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  163. set: function (callback) {
  164. if (this._onExtensionLoadedObserver) {
  165. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  166. }
  167. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  168. },
  169. enumerable: true,
  170. configurable: true
  171. });
  172. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  173. /**
  174. * The loader state or null if not active.
  175. */
  176. get: function () {
  177. return this._loader ? this._loader.state : null;
  178. },
  179. enumerable: true,
  180. configurable: true
  181. });
  182. /**
  183. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  184. */
  185. GLTFFileLoader.prototype.dispose = function () {
  186. if (this._loader) {
  187. this._loader.dispose();
  188. this._loader = null;
  189. }
  190. this.onParsedObservable.clear();
  191. this.onMeshLoadedObservable.clear();
  192. this.onTextureLoadedObservable.clear();
  193. this.onMaterialLoadedObservable.clear();
  194. this.onCompleteObservable.clear();
  195. this.onDisposeObservable.notifyObservers(this);
  196. this.onDisposeObservable.clear();
  197. };
  198. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  199. var _this = this;
  200. return Promise.resolve().then(function () {
  201. var loaderData = _this._parse(data);
  202. _this._loader = _this._getLoader(loaderData);
  203. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  204. });
  205. };
  206. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  207. var _this = this;
  208. return Promise.resolve().then(function () {
  209. var loaderData = _this._parse(data);
  210. _this._loader = _this._getLoader(loaderData);
  211. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  212. });
  213. };
  214. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  215. var _this = this;
  216. return Promise.resolve().then(function () {
  217. var loaderData = _this._parse(data);
  218. _this._loader = _this._getLoader(loaderData);
  219. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  220. var container = new BABYLON.AssetContainer(scene);
  221. Array.prototype.push.apply(container.meshes, result.meshes);
  222. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  223. Array.prototype.push.apply(container.skeletons, result.skeletons);
  224. container.removeAllFromScene();
  225. return container;
  226. });
  227. });
  228. };
  229. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  230. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  231. };
  232. GLTFFileLoader.prototype.createPlugin = function () {
  233. return new GLTFFileLoader();
  234. };
  235. GLTFFileLoader.prototype._parse = function (data) {
  236. var parsedData;
  237. if (data instanceof ArrayBuffer) {
  238. parsedData = GLTFFileLoader._parseBinary(data);
  239. }
  240. else {
  241. parsedData = {
  242. json: JSON.parse(data),
  243. bin: null
  244. };
  245. }
  246. this.onParsedObservable.notifyObservers(parsedData);
  247. return parsedData;
  248. };
  249. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  250. var _this = this;
  251. var loaderVersion = { major: 2, minor: 0 };
  252. var asset = loaderData.json.asset || {};
  253. var version = GLTFFileLoader._parseVersion(asset.version);
  254. if (!version) {
  255. throw new Error("Invalid version: " + asset.version);
  256. }
  257. if (asset.minVersion !== undefined) {
  258. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  259. if (!minVersion) {
  260. throw new Error("Invalid minimum version: " + asset.minVersion);
  261. }
  262. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  263. throw new Error("Incompatible minimum version: " + asset.minVersion);
  264. }
  265. }
  266. var createLoaders = {
  267. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  268. 2: GLTFFileLoader.CreateGLTFLoaderV2
  269. };
  270. var createLoader = createLoaders[version.major];
  271. if (!createLoader) {
  272. throw new Error("Unsupported version: " + asset.version);
  273. }
  274. var loader = createLoader();
  275. loader.coordinateSystemMode = this.coordinateSystemMode;
  276. loader.animationStartMode = this.animationStartMode;
  277. loader.compileMaterials = this.compileMaterials;
  278. loader.useClipPlane = this.useClipPlane;
  279. loader.compileShadowGenerators = this.compileShadowGenerators;
  280. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  281. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  282. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  283. loader.onCompleteObservable.add(function () { return _this.onCompleteObservable.notifyObservers(_this); });
  284. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  285. return loader;
  286. };
  287. GLTFFileLoader._parseBinary = function (data) {
  288. var Binary = {
  289. Magic: 0x46546C67
  290. };
  291. var binaryReader = new BinaryReader(data);
  292. var magic = binaryReader.readUint32();
  293. if (magic !== Binary.Magic) {
  294. throw new Error("Unexpected magic: " + magic);
  295. }
  296. var version = binaryReader.readUint32();
  297. switch (version) {
  298. case 1: return GLTFFileLoader._parseV1(binaryReader);
  299. case 2: return GLTFFileLoader._parseV2(binaryReader);
  300. }
  301. throw new Error("Unsupported version: " + version);
  302. };
  303. GLTFFileLoader._parseV1 = function (binaryReader) {
  304. var ContentFormat = {
  305. JSON: 0
  306. };
  307. var length = binaryReader.readUint32();
  308. if (length != binaryReader.getLength()) {
  309. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  310. }
  311. var contentLength = binaryReader.readUint32();
  312. var contentFormat = binaryReader.readUint32();
  313. var content;
  314. switch (contentFormat) {
  315. case ContentFormat.JSON: {
  316. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  317. break;
  318. }
  319. default: {
  320. throw new Error("Unexpected content format: " + contentFormat);
  321. }
  322. }
  323. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  324. var body = binaryReader.readUint8Array(bytesRemaining);
  325. return {
  326. json: content,
  327. bin: body
  328. };
  329. };
  330. GLTFFileLoader._parseV2 = function (binaryReader) {
  331. var ChunkFormat = {
  332. JSON: 0x4E4F534A,
  333. BIN: 0x004E4942
  334. };
  335. var length = binaryReader.readUint32();
  336. if (length !== binaryReader.getLength()) {
  337. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  338. }
  339. // JSON chunk
  340. var chunkLength = binaryReader.readUint32();
  341. var chunkFormat = binaryReader.readUint32();
  342. if (chunkFormat !== ChunkFormat.JSON) {
  343. throw new Error("First chunk format is not JSON");
  344. }
  345. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  346. // Look for BIN chunk
  347. var bin = null;
  348. while (binaryReader.getPosition() < binaryReader.getLength()) {
  349. var chunkLength_1 = binaryReader.readUint32();
  350. var chunkFormat_1 = binaryReader.readUint32();
  351. switch (chunkFormat_1) {
  352. case ChunkFormat.JSON: {
  353. throw new Error("Unexpected JSON chunk");
  354. }
  355. case ChunkFormat.BIN: {
  356. bin = binaryReader.readUint8Array(chunkLength_1);
  357. break;
  358. }
  359. default: {
  360. // ignore unrecognized chunkFormat
  361. binaryReader.skipBytes(chunkLength_1);
  362. break;
  363. }
  364. }
  365. }
  366. return {
  367. json: json,
  368. bin: bin
  369. };
  370. };
  371. GLTFFileLoader._parseVersion = function (version) {
  372. if (version === "1.0" || version === "1.0.1") {
  373. return {
  374. major: 1,
  375. minor: 0
  376. };
  377. }
  378. var match = (version + "").match(/^(\d+)\.(\d+)/);
  379. if (!match) {
  380. return null;
  381. }
  382. return {
  383. major: parseInt(match[1]),
  384. minor: parseInt(match[2])
  385. };
  386. };
  387. GLTFFileLoader._compareVersion = function (a, b) {
  388. if (a.major > b.major)
  389. return 1;
  390. if (a.major < b.major)
  391. return -1;
  392. if (a.minor > b.minor)
  393. return 1;
  394. if (a.minor < b.minor)
  395. return -1;
  396. return 0;
  397. };
  398. GLTFFileLoader._decodeBufferToText = function (buffer) {
  399. var result = "";
  400. var length = buffer.byteLength;
  401. for (var i = 0; i < length; i++) {
  402. result += String.fromCharCode(buffer[i]);
  403. }
  404. return result;
  405. };
  406. // #endregion
  407. // #region V1 options
  408. GLTFFileLoader.IncrementalLoading = true;
  409. GLTFFileLoader.HomogeneousCoordinates = false;
  410. return GLTFFileLoader;
  411. }());
  412. BABYLON.GLTFFileLoader = GLTFFileLoader;
  413. var BinaryReader = /** @class */ (function () {
  414. function BinaryReader(arrayBuffer) {
  415. this._arrayBuffer = arrayBuffer;
  416. this._dataView = new DataView(arrayBuffer);
  417. this._byteOffset = 0;
  418. }
  419. BinaryReader.prototype.getPosition = function () {
  420. return this._byteOffset;
  421. };
  422. BinaryReader.prototype.getLength = function () {
  423. return this._arrayBuffer.byteLength;
  424. };
  425. BinaryReader.prototype.readUint32 = function () {
  426. var value = this._dataView.getUint32(this._byteOffset, true);
  427. this._byteOffset += 4;
  428. return value;
  429. };
  430. BinaryReader.prototype.readUint8Array = function (length) {
  431. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  432. this._byteOffset += length;
  433. return value;
  434. };
  435. BinaryReader.prototype.skipBytes = function (length) {
  436. this._byteOffset += length;
  437. };
  438. return BinaryReader;
  439. }());
  440. if (BABYLON.SceneLoader) {
  441. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  442. }
  443. })(BABYLON || (BABYLON = {}));
  444. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  445. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  446. var BABYLON;
  447. (function (BABYLON) {
  448. var GLTF1;
  449. (function (GLTF1) {
  450. /**
  451. * Enums
  452. */
  453. var EComponentType;
  454. (function (EComponentType) {
  455. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  456. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  457. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  458. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  459. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  460. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  461. var EShaderType;
  462. (function (EShaderType) {
  463. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  464. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  465. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  466. var EParameterType;
  467. (function (EParameterType) {
  468. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  469. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  470. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  471. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  472. EParameterType[EParameterType["INT"] = 5124] = "INT";
  473. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  474. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  475. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  476. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  477. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  478. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  479. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  480. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  481. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  482. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  483. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  484. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  485. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  486. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  487. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  488. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  489. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  490. var ETextureWrapMode;
  491. (function (ETextureWrapMode) {
  492. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  493. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  494. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  495. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  496. var ETextureFilterType;
  497. (function (ETextureFilterType) {
  498. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  499. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  500. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  501. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  502. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  503. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  504. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  505. var ETextureFormat;
  506. (function (ETextureFormat) {
  507. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  508. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  509. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  510. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  511. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  512. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  513. var ECullingType;
  514. (function (ECullingType) {
  515. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  516. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  517. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  518. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  519. var EBlendingFunction;
  520. (function (EBlendingFunction) {
  521. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  522. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  523. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  524. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  525. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  526. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  527. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  528. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  529. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  530. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  531. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  532. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  533. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  534. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  535. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  536. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  537. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  538. })(BABYLON || (BABYLON = {}));
  539. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  540. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  541. var BABYLON;
  542. (function (BABYLON) {
  543. var GLTF1;
  544. (function (GLTF1) {
  545. /**
  546. * Tokenizer. Used for shaders compatibility
  547. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  548. */
  549. var ETokenType;
  550. (function (ETokenType) {
  551. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  552. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  553. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  554. })(ETokenType || (ETokenType = {}));
  555. var Tokenizer = /** @class */ (function () {
  556. function Tokenizer(toParse) {
  557. this._pos = 0;
  558. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  559. this._toParse = toParse;
  560. this._maxPos = toParse.length;
  561. }
  562. Tokenizer.prototype.getNextToken = function () {
  563. if (this.isEnd())
  564. return ETokenType.END_OF_INPUT;
  565. this.currentString = this.read();
  566. this.currentToken = ETokenType.UNKNOWN;
  567. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  568. this.currentToken = ETokenType.IDENTIFIER;
  569. this.currentIdentifier = this.currentString;
  570. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  571. this.currentIdentifier += this.currentString;
  572. this.forward();
  573. }
  574. }
  575. return this.currentToken;
  576. };
  577. Tokenizer.prototype.peek = function () {
  578. return this._toParse[this._pos];
  579. };
  580. Tokenizer.prototype.read = function () {
  581. return this._toParse[this._pos++];
  582. };
  583. Tokenizer.prototype.forward = function () {
  584. this._pos++;
  585. };
  586. Tokenizer.prototype.isEnd = function () {
  587. return this._pos >= this._maxPos;
  588. };
  589. return Tokenizer;
  590. }());
  591. /**
  592. * Values
  593. */
  594. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  595. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  596. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  597. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  598. /**
  599. * Parse
  600. */
  601. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  602. for (var buf in parsedBuffers) {
  603. var parsedBuffer = parsedBuffers[buf];
  604. gltfRuntime.buffers[buf] = parsedBuffer;
  605. gltfRuntime.buffersCount++;
  606. }
  607. };
  608. var parseShaders = function (parsedShaders, gltfRuntime) {
  609. for (var sha in parsedShaders) {
  610. var parsedShader = parsedShaders[sha];
  611. gltfRuntime.shaders[sha] = parsedShader;
  612. gltfRuntime.shaderscount++;
  613. }
  614. };
  615. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  616. for (var object in parsedObjects) {
  617. var parsedObject = parsedObjects[object];
  618. gltfRuntime[runtimeProperty][object] = parsedObject;
  619. }
  620. };
  621. /**
  622. * Utils
  623. */
  624. var normalizeUVs = function (buffer) {
  625. if (!buffer) {
  626. return;
  627. }
  628. for (var i = 0; i < buffer.length / 2; i++) {
  629. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  630. }
  631. };
  632. var getAttribute = function (attributeParameter) {
  633. if (attributeParameter.semantic === "NORMAL") {
  634. return "normal";
  635. }
  636. else if (attributeParameter.semantic === "POSITION") {
  637. return "position";
  638. }
  639. else if (attributeParameter.semantic === "JOINT") {
  640. return "matricesIndices";
  641. }
  642. else if (attributeParameter.semantic === "WEIGHT") {
  643. return "matricesWeights";
  644. }
  645. else if (attributeParameter.semantic === "COLOR") {
  646. return "color";
  647. }
  648. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  649. var channel = Number(attributeParameter.semantic.split("_")[1]);
  650. return "uv" + (channel === 0 ? "" : channel + 1);
  651. }
  652. return null;
  653. };
  654. /**
  655. * Loads and creates animations
  656. */
  657. var loadAnimations = function (gltfRuntime) {
  658. for (var anim in gltfRuntime.animations) {
  659. var animation = gltfRuntime.animations[anim];
  660. if (!animation.channels || !animation.samplers) {
  661. continue;
  662. }
  663. var lastAnimation = null;
  664. for (var i = 0; i < animation.channels.length; i++) {
  665. // Get parameters and load buffers
  666. var channel = animation.channels[i];
  667. var sampler = animation.samplers[channel.sampler];
  668. if (!sampler) {
  669. continue;
  670. }
  671. var inputData = null;
  672. var outputData = null;
  673. if (animation.parameters) {
  674. inputData = animation.parameters[sampler.input];
  675. outputData = animation.parameters[sampler.output];
  676. }
  677. else {
  678. inputData = sampler.input;
  679. outputData = sampler.output;
  680. }
  681. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  682. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  683. var targetID = channel.target.id;
  684. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  685. if (targetNode === null) {
  686. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  687. }
  688. if (targetNode === null) {
  689. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  690. continue;
  691. }
  692. var isBone = targetNode instanceof BABYLON.Bone;
  693. // Get target path (position, rotation or scaling)
  694. var targetPath = channel.target.path;
  695. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  696. if (targetPathIndex !== -1) {
  697. targetPath = babylonAnimationPaths[targetPathIndex];
  698. }
  699. // Determine animation type
  700. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  701. if (!isBone) {
  702. if (targetPath === "rotationQuaternion") {
  703. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  704. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  705. }
  706. else {
  707. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  708. }
  709. }
  710. // Create animation and key frames
  711. var babylonAnimation = null;
  712. var keys = [];
  713. var arrayOffset = 0;
  714. var modifyKey = false;
  715. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  716. babylonAnimation = lastAnimation;
  717. modifyKey = true;
  718. }
  719. if (!modifyKey) {
  720. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  721. }
  722. // For each frame
  723. for (var j = 0; j < bufferInput.length; j++) {
  724. var value = null;
  725. if (targetPath === "rotationQuaternion") {
  726. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  727. arrayOffset += 4;
  728. }
  729. else {
  730. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  731. arrayOffset += 3;
  732. }
  733. if (isBone) {
  734. var bone = targetNode;
  735. var translation = BABYLON.Vector3.Zero();
  736. var rotationQuaternion = new BABYLON.Quaternion();
  737. var scaling = BABYLON.Vector3.Zero();
  738. // Warning on decompose
  739. var mat = bone.getBaseMatrix();
  740. if (modifyKey && lastAnimation) {
  741. mat = lastAnimation.getKeys()[j].value;
  742. }
  743. mat.decompose(scaling, rotationQuaternion, translation);
  744. if (targetPath === "position") {
  745. translation = value;
  746. }
  747. else if (targetPath === "rotationQuaternion") {
  748. rotationQuaternion = value;
  749. }
  750. else {
  751. scaling = value;
  752. }
  753. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  754. }
  755. if (!modifyKey) {
  756. keys.push({
  757. frame: bufferInput[j],
  758. value: value
  759. });
  760. }
  761. else if (lastAnimation) {
  762. lastAnimation.getKeys()[j].value = value;
  763. }
  764. }
  765. // Finish
  766. if (!modifyKey && babylonAnimation) {
  767. babylonAnimation.setKeys(keys);
  768. targetNode.animations.push(babylonAnimation);
  769. }
  770. lastAnimation = babylonAnimation;
  771. gltfRuntime.scene.stopAnimation(targetNode);
  772. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  773. }
  774. }
  775. };
  776. /**
  777. * Returns the bones transformation matrix
  778. */
  779. var configureBoneTransformation = function (node) {
  780. var mat = null;
  781. if (node.translation || node.rotation || node.scale) {
  782. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  783. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  784. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  785. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  786. }
  787. else {
  788. mat = BABYLON.Matrix.FromArray(node.matrix);
  789. }
  790. return mat;
  791. };
  792. /**
  793. * Returns the parent bone
  794. */
  795. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  796. // Try to find
  797. for (var i = 0; i < newSkeleton.bones.length; i++) {
  798. if (newSkeleton.bones[i].name === jointName) {
  799. return newSkeleton.bones[i];
  800. }
  801. }
  802. // Not found, search in gltf nodes
  803. var nodes = gltfRuntime.nodes;
  804. for (var nde in nodes) {
  805. var node = nodes[nde];
  806. if (!node.jointName) {
  807. continue;
  808. }
  809. var children = node.children;
  810. for (var i = 0; i < children.length; i++) {
  811. var child = gltfRuntime.nodes[children[i]];
  812. if (!child.jointName) {
  813. continue;
  814. }
  815. if (child.jointName === jointName) {
  816. var mat = configureBoneTransformation(node);
  817. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  818. bone.id = nde;
  819. return bone;
  820. }
  821. }
  822. }
  823. return null;
  824. };
  825. /**
  826. * Returns the appropriate root node
  827. */
  828. var getNodeToRoot = function (nodesToRoot, id) {
  829. for (var i = 0; i < nodesToRoot.length; i++) {
  830. var nodeToRoot = nodesToRoot[i];
  831. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  832. var child = nodeToRoot.node.children[j];
  833. if (child === id) {
  834. return nodeToRoot.bone;
  835. }
  836. }
  837. }
  838. return null;
  839. };
  840. /**
  841. * Returns the node with the joint name
  842. */
  843. var getJointNode = function (gltfRuntime, jointName) {
  844. var nodes = gltfRuntime.nodes;
  845. var node = nodes[jointName];
  846. if (node) {
  847. return {
  848. node: node,
  849. id: jointName
  850. };
  851. }
  852. for (var nde in nodes) {
  853. node = nodes[nde];
  854. if (node.jointName === jointName) {
  855. return {
  856. node: node,
  857. id: nde
  858. };
  859. }
  860. }
  861. return null;
  862. };
  863. /**
  864. * Checks if a nodes is in joints
  865. */
  866. var nodeIsInJoints = function (skins, id) {
  867. for (var i = 0; i < skins.jointNames.length; i++) {
  868. if (skins.jointNames[i] === id) {
  869. return true;
  870. }
  871. }
  872. return false;
  873. };
  874. /**
  875. * Fills the nodes to root for bones and builds hierarchy
  876. */
  877. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  878. // Creates nodes for root
  879. for (var nde in gltfRuntime.nodes) {
  880. var node = gltfRuntime.nodes[nde];
  881. var id = nde;
  882. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  883. continue;
  884. }
  885. // Create node to root bone
  886. var mat = configureBoneTransformation(node);
  887. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  888. bone.id = id;
  889. nodesToRoot.push({ bone: bone, node: node, id: id });
  890. }
  891. // Parenting
  892. for (var i = 0; i < nodesToRoot.length; i++) {
  893. var nodeToRoot = nodesToRoot[i];
  894. var children = nodeToRoot.node.children;
  895. for (var j = 0; j < children.length; j++) {
  896. var child = null;
  897. for (var k = 0; k < nodesToRoot.length; k++) {
  898. if (nodesToRoot[k].id === children[j]) {
  899. child = nodesToRoot[k];
  900. break;
  901. }
  902. }
  903. if (child) {
  904. child.bone._parent = nodeToRoot.bone;
  905. nodeToRoot.bone.children.push(child.bone);
  906. }
  907. }
  908. }
  909. };
  910. /**
  911. * Imports a skeleton
  912. */
  913. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  914. if (!newSkeleton) {
  915. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  916. }
  917. if (!skins.babylonSkeleton) {
  918. return newSkeleton;
  919. }
  920. // Find the root bones
  921. var nodesToRoot = [];
  922. var nodesToRootToAdd = [];
  923. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  924. newSkeleton.bones = [];
  925. // Joints
  926. for (var i = 0; i < skins.jointNames.length; i++) {
  927. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  928. if (!jointNode) {
  929. continue;
  930. }
  931. var node = jointNode.node;
  932. if (!node) {
  933. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  934. continue;
  935. }
  936. var id = jointNode.id;
  937. // Optimize, if the bone already exists...
  938. var existingBone = gltfRuntime.scene.getBoneByID(id);
  939. if (existingBone) {
  940. newSkeleton.bones.push(existingBone);
  941. continue;
  942. }
  943. // Search for parent bone
  944. var foundBone = false;
  945. var parentBone = null;
  946. for (var j = 0; j < i; j++) {
  947. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  948. if (!jointNode_1) {
  949. continue;
  950. }
  951. var joint = jointNode_1.node;
  952. if (!joint) {
  953. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  954. continue;
  955. }
  956. var children = joint.children;
  957. if (!children) {
  958. continue;
  959. }
  960. foundBone = false;
  961. for (var k = 0; k < children.length; k++) {
  962. if (children[k] === id) {
  963. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  964. foundBone = true;
  965. break;
  966. }
  967. }
  968. if (foundBone) {
  969. break;
  970. }
  971. }
  972. // Create bone
  973. var mat = configureBoneTransformation(node);
  974. if (!parentBone && nodesToRoot.length > 0) {
  975. parentBone = getNodeToRoot(nodesToRoot, id);
  976. if (parentBone) {
  977. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  978. nodesToRootToAdd.push(parentBone);
  979. }
  980. }
  981. }
  982. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  983. bone.id = id;
  984. }
  985. // Polish
  986. var bones = newSkeleton.bones;
  987. newSkeleton.bones = [];
  988. for (var i = 0; i < skins.jointNames.length; i++) {
  989. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  990. if (!jointNode) {
  991. continue;
  992. }
  993. for (var j = 0; j < bones.length; j++) {
  994. if (bones[j].id === jointNode.id) {
  995. newSkeleton.bones.push(bones[j]);
  996. break;
  997. }
  998. }
  999. }
  1000. newSkeleton.prepare();
  1001. // Finish
  1002. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  1003. newSkeleton.bones.push(nodesToRootToAdd[i]);
  1004. }
  1005. return newSkeleton;
  1006. };
  1007. /**
  1008. * Imports a mesh and its geometries
  1009. */
  1010. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  1011. if (!newMesh) {
  1012. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1013. newMesh.id = id;
  1014. }
  1015. if (!node.babylonNode) {
  1016. return newMesh;
  1017. }
  1018. var subMaterials = [];
  1019. var vertexData = null;
  1020. var verticesStarts = new Array();
  1021. var verticesCounts = new Array();
  1022. var indexStarts = new Array();
  1023. var indexCounts = new Array();
  1024. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1025. var meshID = meshes[meshIndex];
  1026. var mesh = gltfRuntime.meshes[meshID];
  1027. if (!mesh) {
  1028. continue;
  1029. }
  1030. // Positions, normals and UVs
  1031. for (var i = 0; i < mesh.primitives.length; i++) {
  1032. // Temporary vertex data
  1033. var tempVertexData = new BABYLON.VertexData();
  1034. var primitive = mesh.primitives[i];
  1035. if (primitive.mode !== 4) {
  1036. // continue;
  1037. }
  1038. var attributes = primitive.attributes;
  1039. var accessor = null;
  1040. var buffer = null;
  1041. // Set positions, normal and uvs
  1042. for (var semantic in attributes) {
  1043. // Link accessor and buffer view
  1044. accessor = gltfRuntime.accessors[attributes[semantic]];
  1045. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1046. if (semantic === "NORMAL") {
  1047. tempVertexData.normals = new Float32Array(buffer.length);
  1048. tempVertexData.normals.set(buffer);
  1049. }
  1050. else if (semantic === "POSITION") {
  1051. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  1052. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  1053. for (var j = 0; j < buffer.length; j += 4) {
  1054. tempVertexData.positions[j] = buffer[j];
  1055. tempVertexData.positions[j + 1] = buffer[j + 1];
  1056. tempVertexData.positions[j + 2] = buffer[j + 2];
  1057. }
  1058. }
  1059. else {
  1060. tempVertexData.positions = new Float32Array(buffer.length);
  1061. tempVertexData.positions.set(buffer);
  1062. }
  1063. verticesCounts.push(tempVertexData.positions.length);
  1064. }
  1065. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  1066. var channel = Number(semantic.split("_")[1]);
  1067. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  1068. var uvs = new Float32Array(buffer.length);
  1069. uvs.set(buffer);
  1070. normalizeUVs(uvs);
  1071. tempVertexData.set(uvs, uvKind);
  1072. }
  1073. else if (semantic === "JOINT") {
  1074. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  1075. tempVertexData.matricesIndices.set(buffer);
  1076. }
  1077. else if (semantic === "WEIGHT") {
  1078. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  1079. tempVertexData.matricesWeights.set(buffer);
  1080. }
  1081. else if (semantic === "COLOR") {
  1082. tempVertexData.colors = new Float32Array(buffer.length);
  1083. tempVertexData.colors.set(buffer);
  1084. }
  1085. }
  1086. // Indices
  1087. accessor = gltfRuntime.accessors[primitive.indices];
  1088. if (accessor) {
  1089. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1090. tempVertexData.indices = new Int32Array(buffer.length);
  1091. tempVertexData.indices.set(buffer);
  1092. indexCounts.push(tempVertexData.indices.length);
  1093. }
  1094. else {
  1095. // Set indices on the fly
  1096. var indices = [];
  1097. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  1098. indices.push(j);
  1099. }
  1100. tempVertexData.indices = new Int32Array(indices);
  1101. indexCounts.push(tempVertexData.indices.length);
  1102. }
  1103. if (!vertexData) {
  1104. vertexData = tempVertexData;
  1105. }
  1106. else {
  1107. vertexData.merge(tempVertexData);
  1108. }
  1109. // Sub material
  1110. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  1111. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  1112. // Update vertices start and index start
  1113. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  1114. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  1115. }
  1116. }
  1117. var material;
  1118. if (subMaterials.length > 1) {
  1119. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  1120. material.subMaterials = subMaterials;
  1121. }
  1122. else {
  1123. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  1124. }
  1125. if (subMaterials.length === 1) {
  1126. material = subMaterials[0];
  1127. }
  1128. if (!newMesh.material) {
  1129. newMesh.material = material;
  1130. }
  1131. // Apply geometry
  1132. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  1133. newMesh.computeWorldMatrix(true);
  1134. // Apply submeshes
  1135. newMesh.subMeshes = [];
  1136. var index = 0;
  1137. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1138. var meshID = meshes[meshIndex];
  1139. var mesh = gltfRuntime.meshes[meshID];
  1140. if (!mesh) {
  1141. continue;
  1142. }
  1143. for (var i = 0; i < mesh.primitives.length; i++) {
  1144. if (mesh.primitives[i].mode !== 4) {
  1145. //continue;
  1146. }
  1147. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  1148. index++;
  1149. }
  1150. }
  1151. // Finish
  1152. return newMesh;
  1153. };
  1154. /**
  1155. * Configure node transformation from position, rotation and scaling
  1156. */
  1157. var configureNode = function (newNode, position, rotation, scaling) {
  1158. if (newNode.position) {
  1159. newNode.position = position;
  1160. }
  1161. if (newNode.rotationQuaternion || newNode.rotation) {
  1162. newNode.rotationQuaternion = rotation;
  1163. }
  1164. if (newNode.scaling) {
  1165. newNode.scaling = scaling;
  1166. }
  1167. };
  1168. /**
  1169. * Configures node from transformation matrix
  1170. */
  1171. var configureNodeFromMatrix = function (newNode, node, parent) {
  1172. if (node.matrix) {
  1173. var position = new BABYLON.Vector3(0, 0, 0);
  1174. var rotation = new BABYLON.Quaternion();
  1175. var scaling = new BABYLON.Vector3(0, 0, 0);
  1176. var mat = BABYLON.Matrix.FromArray(node.matrix);
  1177. mat.decompose(scaling, rotation, position);
  1178. configureNode(newNode, position, rotation, scaling);
  1179. }
  1180. else if (node.translation && node.rotation && node.scale) {
  1181. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  1182. }
  1183. newNode.computeWorldMatrix(true);
  1184. };
  1185. /**
  1186. * Imports a node
  1187. */
  1188. var importNode = function (gltfRuntime, node, id, parent) {
  1189. var lastNode = null;
  1190. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  1191. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  1192. return null;
  1193. }
  1194. }
  1195. // Meshes
  1196. if (node.skin) {
  1197. if (node.meshes) {
  1198. var skin = gltfRuntime.skins[node.skin];
  1199. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  1200. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  1201. if (newMesh.skeleton === null) {
  1202. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  1203. if (!skin.babylonSkeleton) {
  1204. skin.babylonSkeleton = newMesh.skeleton;
  1205. }
  1206. }
  1207. lastNode = newMesh;
  1208. }
  1209. }
  1210. else if (node.meshes) {
  1211. /**
  1212. * Improve meshes property
  1213. */
  1214. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  1215. lastNode = newMesh;
  1216. }
  1217. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1218. var light = gltfRuntime.lights[node.light];
  1219. if (light) {
  1220. if (light.type === "ambient") {
  1221. var ambienLight = light[light.type];
  1222. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1223. hemiLight.name = node.name || "";
  1224. if (ambienLight.color) {
  1225. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  1226. }
  1227. lastNode = hemiLight;
  1228. }
  1229. else if (light.type === "directional") {
  1230. var directionalLight = light[light.type];
  1231. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1232. dirLight.name = node.name || "";
  1233. if (directionalLight.color) {
  1234. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  1235. }
  1236. lastNode = dirLight;
  1237. }
  1238. else if (light.type === "point") {
  1239. var pointLight = light[light.type];
  1240. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1241. ptLight.name = node.name || "";
  1242. if (pointLight.color) {
  1243. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  1244. }
  1245. lastNode = ptLight;
  1246. }
  1247. else if (light.type === "spot") {
  1248. var spotLight = light[light.type];
  1249. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  1250. spLight.name = node.name || "";
  1251. if (spotLight.color) {
  1252. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  1253. }
  1254. if (spotLight.fallOfAngle) {
  1255. spLight.angle = spotLight.fallOfAngle;
  1256. }
  1257. if (spotLight.fallOffExponent) {
  1258. spLight.exponent = spotLight.fallOffExponent;
  1259. }
  1260. lastNode = spLight;
  1261. }
  1262. }
  1263. }
  1264. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1265. var camera = gltfRuntime.cameras[node.camera];
  1266. if (camera) {
  1267. if (camera.type === "orthographic") {
  1268. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1269. orthoCamera.name = node.name || "";
  1270. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1271. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1272. lastNode = orthoCamera;
  1273. }
  1274. else if (camera.type === "perspective") {
  1275. var perspectiveCamera = camera[camera.type];
  1276. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1277. persCamera.name = node.name || "";
  1278. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1279. if (!perspectiveCamera.aspectRatio) {
  1280. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  1281. }
  1282. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  1283. persCamera.maxZ = perspectiveCamera.zfar;
  1284. persCamera.minZ = perspectiveCamera.znear;
  1285. }
  1286. lastNode = persCamera;
  1287. }
  1288. }
  1289. }
  1290. // Empty node
  1291. if (!node.jointName) {
  1292. if (node.babylonNode) {
  1293. return node.babylonNode;
  1294. }
  1295. else if (lastNode === null) {
  1296. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1297. node.babylonNode = dummy;
  1298. lastNode = dummy;
  1299. }
  1300. }
  1301. if (lastNode !== null) {
  1302. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  1303. configureNodeFromMatrix(lastNode, node, parent);
  1304. }
  1305. else {
  1306. var translation = node.translation || [0, 0, 0];
  1307. var rotation = node.rotation || [0, 0, 0, 1];
  1308. var scale = node.scale || [1, 1, 1];
  1309. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  1310. }
  1311. lastNode.updateCache(true);
  1312. node.babylonNode = lastNode;
  1313. }
  1314. return lastNode;
  1315. };
  1316. /**
  1317. * Traverses nodes and creates them
  1318. */
  1319. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  1320. if (meshIncluded === void 0) { meshIncluded = false; }
  1321. var node = gltfRuntime.nodes[id];
  1322. var newNode = null;
  1323. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  1324. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  1325. meshIncluded = true;
  1326. }
  1327. else {
  1328. meshIncluded = false;
  1329. }
  1330. }
  1331. else {
  1332. meshIncluded = true;
  1333. }
  1334. if (!node.jointName && meshIncluded) {
  1335. newNode = importNode(gltfRuntime, node, id, parent);
  1336. if (newNode !== null) {
  1337. newNode.id = id;
  1338. newNode.parent = parent;
  1339. }
  1340. }
  1341. if (node.children) {
  1342. for (var i = 0; i < node.children.length; i++) {
  1343. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  1344. }
  1345. }
  1346. };
  1347. /**
  1348. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  1349. */
  1350. var postLoad = function (gltfRuntime) {
  1351. // Nodes
  1352. var currentScene = gltfRuntime.currentScene;
  1353. if (currentScene) {
  1354. for (var i = 0; i < currentScene.nodes.length; i++) {
  1355. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1356. }
  1357. }
  1358. else {
  1359. for (var thing in gltfRuntime.scenes) {
  1360. currentScene = gltfRuntime.scenes[thing];
  1361. for (var i = 0; i < currentScene.nodes.length; i++) {
  1362. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1363. }
  1364. }
  1365. }
  1366. // Set animations
  1367. loadAnimations(gltfRuntime);
  1368. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  1369. var skeleton = gltfRuntime.scene.skeletons[i];
  1370. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1371. }
  1372. };
  1373. /**
  1374. * onBind shaderrs callback to set uniforms and matrices
  1375. */
  1376. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  1377. var materialValues = material.values || technique.parameters;
  1378. for (var unif in unTreatedUniforms) {
  1379. var uniform = unTreatedUniforms[unif];
  1380. var type = uniform.type;
  1381. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  1382. if (uniform.semantic && !uniform.source && !uniform.node) {
  1383. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1384. }
  1385. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1386. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  1387. if (source === null) {
  1388. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  1389. }
  1390. if (source === null) {
  1391. continue;
  1392. }
  1393. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1394. }
  1395. }
  1396. else {
  1397. var value = materialValues[technique.uniforms[unif]];
  1398. if (!value) {
  1399. continue;
  1400. }
  1401. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1402. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  1403. if (texture === null || texture === undefined) {
  1404. continue;
  1405. }
  1406. shaderMaterial.getEffect().setTexture(unif, texture);
  1407. }
  1408. else {
  1409. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  1410. }
  1411. }
  1412. }
  1413. onSuccess(shaderMaterial);
  1414. };
  1415. /**
  1416. * Prepare uniforms to send the only one time
  1417. * Loads the appropriate textures
  1418. */
  1419. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1420. var materialValues = material.values || technique.parameters;
  1421. var techniqueUniforms = technique.uniforms;
  1422. /**
  1423. * Prepare values here (not matrices)
  1424. */
  1425. for (var unif in unTreatedUniforms) {
  1426. var uniform = unTreatedUniforms[unif];
  1427. var type = uniform.type;
  1428. var value = materialValues[techniqueUniforms[unif]];
  1429. if (value === undefined) {
  1430. // In case the value is the same for all materials
  1431. value = uniform.value;
  1432. }
  1433. if (!value) {
  1434. continue;
  1435. }
  1436. var onLoadTexture = function (uniformName) {
  1437. return function (texture) {
  1438. if (uniform.value && uniformName) {
  1439. // Static uniform
  1440. shaderMaterial.setTexture(uniformName, texture);
  1441. delete unTreatedUniforms[uniformName];
  1442. }
  1443. };
  1444. };
  1445. // Texture (sampler2D)
  1446. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1447. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  1448. }
  1449. else {
  1450. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1451. // Static uniform
  1452. delete unTreatedUniforms[unif];
  1453. }
  1454. }
  1455. }
  1456. };
  1457. /**
  1458. * Shader compilation failed
  1459. */
  1460. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1461. return function (effect, error) {
  1462. shaderMaterial.dispose(true);
  1463. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1464. };
  1465. };
  1466. /**
  1467. * Shader compilation success
  1468. */
  1469. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1470. return function (_) {
  1471. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1472. shaderMaterial.onBind = function (mesh) {
  1473. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1474. };
  1475. };
  1476. };
  1477. /**
  1478. * Returns the appropriate uniform if already handled by babylon
  1479. */
  1480. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1481. for (var unif in technique.uniforms) {
  1482. var uniform = technique.uniforms[unif];
  1483. var uniformParameter = technique.parameters[uniform];
  1484. if (tokenizer.currentIdentifier === unif) {
  1485. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1486. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1487. if (transformIndex !== -1) {
  1488. delete unTreatedUniforms[unif];
  1489. return babylonTransforms[transformIndex];
  1490. }
  1491. }
  1492. }
  1493. }
  1494. return tokenizer.currentIdentifier;
  1495. };
  1496. /**
  1497. * All shaders loaded. Create materials one by one
  1498. */
  1499. var importMaterials = function (gltfRuntime) {
  1500. // Create materials
  1501. for (var mat in gltfRuntime.materials) {
  1502. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1503. }
  1504. };
  1505. /**
  1506. * Implementation of the base glTF spec
  1507. */
  1508. var GLTFLoaderBase = /** @class */ (function () {
  1509. function GLTFLoaderBase() {
  1510. }
  1511. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1512. var gltfRuntime = {
  1513. extensions: {},
  1514. accessors: {},
  1515. buffers: {},
  1516. bufferViews: {},
  1517. meshes: {},
  1518. lights: {},
  1519. cameras: {},
  1520. nodes: {},
  1521. images: {},
  1522. textures: {},
  1523. shaders: {},
  1524. programs: {},
  1525. samplers: {},
  1526. techniques: {},
  1527. materials: {},
  1528. animations: {},
  1529. skins: {},
  1530. extensionsUsed: [],
  1531. scenes: {},
  1532. buffersCount: 0,
  1533. shaderscount: 0,
  1534. scene: scene,
  1535. rootUrl: rootUrl,
  1536. loadedBufferCount: 0,
  1537. loadedBufferViews: {},
  1538. loadedShaderCount: 0,
  1539. importOnlyMeshes: false,
  1540. dummyNodes: []
  1541. };
  1542. // Parse
  1543. if (parsedData.extensions) {
  1544. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1545. }
  1546. if (parsedData.extensionsUsed) {
  1547. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1548. }
  1549. if (parsedData.buffers) {
  1550. parseBuffers(parsedData.buffers, gltfRuntime);
  1551. }
  1552. if (parsedData.bufferViews) {
  1553. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1554. }
  1555. if (parsedData.accessors) {
  1556. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1557. }
  1558. if (parsedData.meshes) {
  1559. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1560. }
  1561. if (parsedData.lights) {
  1562. parseObject(parsedData.lights, "lights", gltfRuntime);
  1563. }
  1564. if (parsedData.cameras) {
  1565. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1566. }
  1567. if (parsedData.nodes) {
  1568. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1569. }
  1570. if (parsedData.images) {
  1571. parseObject(parsedData.images, "images", gltfRuntime);
  1572. }
  1573. if (parsedData.textures) {
  1574. parseObject(parsedData.textures, "textures", gltfRuntime);
  1575. }
  1576. if (parsedData.shaders) {
  1577. parseShaders(parsedData.shaders, gltfRuntime);
  1578. }
  1579. if (parsedData.programs) {
  1580. parseObject(parsedData.programs, "programs", gltfRuntime);
  1581. }
  1582. if (parsedData.samplers) {
  1583. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1584. }
  1585. if (parsedData.techniques) {
  1586. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1587. }
  1588. if (parsedData.materials) {
  1589. parseObject(parsedData.materials, "materials", gltfRuntime);
  1590. }
  1591. if (parsedData.animations) {
  1592. parseObject(parsedData.animations, "animations", gltfRuntime);
  1593. }
  1594. if (parsedData.skins) {
  1595. parseObject(parsedData.skins, "skins", gltfRuntime);
  1596. }
  1597. if (parsedData.scenes) {
  1598. gltfRuntime.scenes = parsedData.scenes;
  1599. }
  1600. if (parsedData.scene && parsedData.scenes) {
  1601. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1602. }
  1603. return gltfRuntime;
  1604. };
  1605. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1606. var buffer = gltfRuntime.buffers[id];
  1607. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  1608. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  1609. }
  1610. else {
  1611. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  1612. if (request) {
  1613. onError(request.status + " " + request.statusText);
  1614. }
  1615. });
  1616. }
  1617. };
  1618. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1619. var texture = gltfRuntime.textures[id];
  1620. if (!texture || !texture.source) {
  1621. onError("");
  1622. return;
  1623. }
  1624. if (texture.babylonTexture) {
  1625. onSuccess(null);
  1626. return;
  1627. }
  1628. var source = gltfRuntime.images[texture.source];
  1629. if (BABYLON.Tools.IsBase64(source.uri)) {
  1630. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  1631. }
  1632. else {
  1633. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  1634. if (request) {
  1635. onError(request.status + " " + request.statusText);
  1636. }
  1637. });
  1638. }
  1639. };
  1640. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1641. var texture = gltfRuntime.textures[id];
  1642. if (texture.babylonTexture) {
  1643. onSuccess(texture.babylonTexture);
  1644. return;
  1645. }
  1646. var sampler = gltfRuntime.samplers[texture.sampler];
  1647. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1648. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1649. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1650. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1651. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1652. var blob = new Blob([buffer]);
  1653. var blobURL = URL.createObjectURL(blob);
  1654. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1655. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1656. if (sampler.wrapS !== undefined) {
  1657. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  1658. }
  1659. if (sampler.wrapT !== undefined) {
  1660. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  1661. }
  1662. newTexture.name = id;
  1663. texture.babylonTexture = newTexture;
  1664. onSuccess(newTexture);
  1665. };
  1666. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1667. var shader = gltfRuntime.shaders[id];
  1668. if (BABYLON.Tools.IsBase64(shader.uri)) {
  1669. var shaderString = atob(shader.uri.split(",")[1]);
  1670. onSuccess(shaderString);
  1671. }
  1672. else {
  1673. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  1674. if (request) {
  1675. onError(request.status + " " + request.statusText);
  1676. }
  1677. });
  1678. }
  1679. };
  1680. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1681. var material = gltfRuntime.materials[id];
  1682. if (!material.technique) {
  1683. if (onError) {
  1684. onError("No technique found.");
  1685. }
  1686. return;
  1687. }
  1688. var technique = gltfRuntime.techniques[material.technique];
  1689. if (!technique) {
  1690. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1691. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  1692. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1693. onSuccess(defaultMaterial);
  1694. return;
  1695. }
  1696. var program = gltfRuntime.programs[technique.program];
  1697. var states = technique.states;
  1698. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1699. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1700. var newVertexShader = "";
  1701. var newPixelShader = "";
  1702. var vertexTokenizer = new Tokenizer(vertexShader);
  1703. var pixelTokenizer = new Tokenizer(pixelShader);
  1704. var unTreatedUniforms = {};
  1705. var uniforms = [];
  1706. var attributes = [];
  1707. var samplers = [];
  1708. // Fill uniform, sampler2D and attributes
  1709. for (var unif in technique.uniforms) {
  1710. var uniform = technique.uniforms[unif];
  1711. var uniformParameter = technique.parameters[uniform];
  1712. unTreatedUniforms[unif] = uniformParameter;
  1713. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1714. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1715. if (transformIndex !== -1) {
  1716. uniforms.push(babylonTransforms[transformIndex]);
  1717. delete unTreatedUniforms[unif];
  1718. }
  1719. else {
  1720. uniforms.push(unif);
  1721. }
  1722. }
  1723. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  1724. samplers.push(unif);
  1725. }
  1726. else {
  1727. uniforms.push(unif);
  1728. }
  1729. }
  1730. for (var attr in technique.attributes) {
  1731. var attribute = technique.attributes[attr];
  1732. var attributeParameter = technique.parameters[attribute];
  1733. if (attributeParameter.semantic) {
  1734. attributes.push(getAttribute(attributeParameter));
  1735. }
  1736. }
  1737. // Configure vertex shader
  1738. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1739. var tokenType = vertexTokenizer.currentToken;
  1740. if (tokenType !== ETokenType.IDENTIFIER) {
  1741. newVertexShader += vertexTokenizer.currentString;
  1742. continue;
  1743. }
  1744. var foundAttribute = false;
  1745. for (var attr in technique.attributes) {
  1746. var attribute = technique.attributes[attr];
  1747. var attributeParameter = technique.parameters[attribute];
  1748. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1749. newVertexShader += getAttribute(attributeParameter);
  1750. foundAttribute = true;
  1751. break;
  1752. }
  1753. }
  1754. if (foundAttribute) {
  1755. continue;
  1756. }
  1757. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1758. }
  1759. // Configure pixel shader
  1760. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1761. var tokenType = pixelTokenizer.currentToken;
  1762. if (tokenType !== ETokenType.IDENTIFIER) {
  1763. newPixelShader += pixelTokenizer.currentString;
  1764. continue;
  1765. }
  1766. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1767. }
  1768. // Create shader material
  1769. var shaderPath = {
  1770. vertex: program.vertexShader + id,
  1771. fragment: program.fragmentShader + id
  1772. };
  1773. var options = {
  1774. attributes: attributes,
  1775. uniforms: uniforms,
  1776. samplers: samplers,
  1777. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1778. };
  1779. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1780. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1781. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1782. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1783. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1784. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1785. if (states && states.functions) {
  1786. var functions = states.functions;
  1787. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  1788. shaderMaterial.backFaceCulling = false;
  1789. }
  1790. var blendFunc = functions.blendFuncSeparate;
  1791. if (blendFunc) {
  1792. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1793. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1794. }
  1795. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1796. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  1797. }
  1798. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1799. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  1800. }
  1801. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1802. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  1803. }
  1804. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1805. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  1806. }
  1807. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1808. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  1809. }
  1810. }
  1811. }
  1812. };
  1813. return GLTFLoaderBase;
  1814. }());
  1815. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  1816. /**
  1817. * glTF V1 Loader
  1818. */
  1819. var GLTFLoader = /** @class */ (function () {
  1820. function GLTFLoader() {
  1821. // #region Stubs for IGLTFLoader interface
  1822. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  1823. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  1824. this.compileMaterials = false;
  1825. this.useClipPlane = false;
  1826. this.compileShadowGenerators = false;
  1827. this.onDisposeObservable = new BABYLON.Observable();
  1828. this.onMeshLoadedObservable = new BABYLON.Observable();
  1829. this.onTextureLoadedObservable = new BABYLON.Observable();
  1830. this.onMaterialLoadedObservable = new BABYLON.Observable();
  1831. this.onCompleteObservable = new BABYLON.Observable();
  1832. this.onExtensionLoadedObservable = new BABYLON.Observable();
  1833. this.state = null;
  1834. }
  1835. GLTFLoader.RegisterExtension = function (extension) {
  1836. if (GLTFLoader.Extensions[extension.name]) {
  1837. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1838. return;
  1839. }
  1840. GLTFLoader.Extensions[extension.name] = extension;
  1841. };
  1842. GLTFLoader.prototype.dispose = function () { };
  1843. // #endregion
  1844. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  1845. var _this = this;
  1846. scene.useRightHandedSystem = true;
  1847. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1848. gltfRuntime.importOnlyMeshes = true;
  1849. if (meshesNames === "") {
  1850. gltfRuntime.importMeshesNames = [];
  1851. }
  1852. else if (typeof meshesNames === "string") {
  1853. gltfRuntime.importMeshesNames = [meshesNames];
  1854. }
  1855. else if (meshesNames && !(meshesNames instanceof Array)) {
  1856. gltfRuntime.importMeshesNames = [meshesNames];
  1857. }
  1858. else {
  1859. gltfRuntime.importMeshesNames = [];
  1860. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1861. }
  1862. // Create nodes
  1863. _this._createNodes(gltfRuntime);
  1864. var meshes = new Array();
  1865. var skeletons = new Array();
  1866. // Fill arrays of meshes and skeletons
  1867. for (var nde in gltfRuntime.nodes) {
  1868. var node = gltfRuntime.nodes[nde];
  1869. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1870. meshes.push(node.babylonNode);
  1871. }
  1872. }
  1873. for (var skl in gltfRuntime.skins) {
  1874. var skin = gltfRuntime.skins[skl];
  1875. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1876. skeletons.push(skin.babylonSkeleton);
  1877. }
  1878. }
  1879. // Load buffers, shaders, materials, etc.
  1880. _this._loadBuffersAsync(gltfRuntime, function () {
  1881. _this._loadShadersAsync(gltfRuntime, function () {
  1882. importMaterials(gltfRuntime);
  1883. postLoad(gltfRuntime);
  1884. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1885. onSuccess(meshes, [], skeletons);
  1886. }
  1887. });
  1888. }, onProgress);
  1889. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1890. onSuccess(meshes, [], skeletons);
  1891. }
  1892. }, onError);
  1893. return true;
  1894. };
  1895. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  1896. var _this = this;
  1897. return new Promise(function (resolve, reject) {
  1898. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  1899. resolve({
  1900. meshes: meshes,
  1901. particleSystems: particleSystems,
  1902. skeletons: skeletons
  1903. });
  1904. }, onProgress, function (message) {
  1905. reject(new Error(message));
  1906. });
  1907. });
  1908. };
  1909. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  1910. var _this = this;
  1911. scene.useRightHandedSystem = true;
  1912. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1913. // Load runtime extensios
  1914. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  1915. // Create nodes
  1916. _this._createNodes(gltfRuntime);
  1917. // Load buffers, shaders, materials, etc.
  1918. _this._loadBuffersAsync(gltfRuntime, function () {
  1919. _this._loadShadersAsync(gltfRuntime, function () {
  1920. importMaterials(gltfRuntime);
  1921. postLoad(gltfRuntime);
  1922. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  1923. onSuccess();
  1924. }
  1925. });
  1926. });
  1927. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  1928. onSuccess();
  1929. }
  1930. }, onError);
  1931. }, onError);
  1932. };
  1933. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  1934. var _this = this;
  1935. return new Promise(function (resolve, reject) {
  1936. _this._loadAsync(scene, data, rootUrl, function () {
  1937. resolve();
  1938. }, onProgress, function (message) {
  1939. reject(new Error(message));
  1940. });
  1941. });
  1942. };
  1943. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1944. var hasShaders = false;
  1945. var processShader = function (sha, shader) {
  1946. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1947. gltfRuntime.loadedShaderCount++;
  1948. if (shaderString) {
  1949. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1950. }
  1951. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1952. onload();
  1953. }
  1954. }, function () {
  1955. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1956. });
  1957. };
  1958. for (var sha in gltfRuntime.shaders) {
  1959. hasShaders = true;
  1960. var shader = gltfRuntime.shaders[sha];
  1961. if (shader) {
  1962. processShader.bind(this, sha, shader)();
  1963. }
  1964. else {
  1965. BABYLON.Tools.Error("No shader named: " + sha);
  1966. }
  1967. }
  1968. if (!hasShaders) {
  1969. onload();
  1970. }
  1971. };
  1972. ;
  1973. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  1974. var hasBuffers = false;
  1975. var processBuffer = function (buf, buffer) {
  1976. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  1977. gltfRuntime.loadedBufferCount++;
  1978. if (bufferView) {
  1979. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1980. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1981. }
  1982. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1983. }
  1984. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1985. onLoad();
  1986. }
  1987. }, function () {
  1988. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1989. });
  1990. };
  1991. for (var buf in gltfRuntime.buffers) {
  1992. hasBuffers = true;
  1993. var buffer = gltfRuntime.buffers[buf];
  1994. if (buffer) {
  1995. processBuffer.bind(this, buf, buffer)();
  1996. }
  1997. else {
  1998. BABYLON.Tools.Error("No buffer named: " + buf);
  1999. }
  2000. }
  2001. if (!hasBuffers) {
  2002. onLoad();
  2003. }
  2004. };
  2005. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  2006. var currentScene = gltfRuntime.currentScene;
  2007. if (currentScene) {
  2008. // Only one scene even if multiple scenes are defined
  2009. for (var i = 0; i < currentScene.nodes.length; i++) {
  2010. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2011. }
  2012. }
  2013. else {
  2014. // Load all scenes
  2015. for (var thing in gltfRuntime.scenes) {
  2016. currentScene = gltfRuntime.scenes[thing];
  2017. for (var i = 0; i < currentScene.nodes.length; i++) {
  2018. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2019. }
  2020. }
  2021. }
  2022. };
  2023. GLTFLoader.Extensions = {};
  2024. return GLTFLoader;
  2025. }());
  2026. GLTF1.GLTFLoader = GLTFLoader;
  2027. ;
  2028. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  2029. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2030. })(BABYLON || (BABYLON = {}));
  2031. //# sourceMappingURL=babylon.glTFLoader.js.map
  2032. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2033. var BABYLON;
  2034. (function (BABYLON) {
  2035. var GLTF1;
  2036. (function (GLTF1) {
  2037. /**
  2038. * Utils functions for GLTF
  2039. */
  2040. var GLTFUtils = /** @class */ (function () {
  2041. function GLTFUtils() {
  2042. }
  2043. /**
  2044. * Sets the given "parameter" matrix
  2045. * @param scene: the {BABYLON.Scene} object
  2046. * @param source: the source node where to pick the matrix
  2047. * @param parameter: the GLTF technique parameter
  2048. * @param uniformName: the name of the shader's uniform
  2049. * @param shaderMaterial: the shader material
  2050. */
  2051. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  2052. var mat = null;
  2053. if (parameter.semantic === "MODEL") {
  2054. mat = source.getWorldMatrix();
  2055. }
  2056. else if (parameter.semantic === "PROJECTION") {
  2057. mat = scene.getProjectionMatrix();
  2058. }
  2059. else if (parameter.semantic === "VIEW") {
  2060. mat = scene.getViewMatrix();
  2061. }
  2062. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  2063. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  2064. }
  2065. else if (parameter.semantic === "MODELVIEW") {
  2066. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  2067. }
  2068. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  2069. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  2070. }
  2071. else if (parameter.semantic === "MODELINVERSE") {
  2072. mat = source.getWorldMatrix().invert();
  2073. }
  2074. else if (parameter.semantic === "VIEWINVERSE") {
  2075. mat = scene.getViewMatrix().invert();
  2076. }
  2077. else if (parameter.semantic === "PROJECTIONINVERSE") {
  2078. mat = scene.getProjectionMatrix().invert();
  2079. }
  2080. else if (parameter.semantic === "MODELVIEWINVERSE") {
  2081. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  2082. }
  2083. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  2084. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  2085. }
  2086. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  2087. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  2088. }
  2089. else {
  2090. debugger;
  2091. }
  2092. if (mat) {
  2093. switch (parameter.type) {
  2094. case GLTF1.EParameterType.FLOAT_MAT2:
  2095. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  2096. break;
  2097. case GLTF1.EParameterType.FLOAT_MAT3:
  2098. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  2099. break;
  2100. case GLTF1.EParameterType.FLOAT_MAT4:
  2101. shaderMaterial.setMatrix(uniformName, mat);
  2102. break;
  2103. default: break;
  2104. }
  2105. }
  2106. };
  2107. /**
  2108. * Sets the given "parameter" matrix
  2109. * @param shaderMaterial: the shader material
  2110. * @param uniform: the name of the shader's uniform
  2111. * @param value: the value of the uniform
  2112. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  2113. */
  2114. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  2115. switch (type) {
  2116. case GLTF1.EParameterType.FLOAT:
  2117. shaderMaterial.setFloat(uniform, value);
  2118. return true;
  2119. case GLTF1.EParameterType.FLOAT_VEC2:
  2120. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  2121. return true;
  2122. case GLTF1.EParameterType.FLOAT_VEC3:
  2123. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  2124. return true;
  2125. case GLTF1.EParameterType.FLOAT_VEC4:
  2126. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  2127. return true;
  2128. default: return false;
  2129. }
  2130. };
  2131. /**
  2132. * Returns the wrap mode of the texture
  2133. * @param mode: the mode value
  2134. */
  2135. GLTFUtils.GetWrapMode = function (mode) {
  2136. switch (mode) {
  2137. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  2138. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  2139. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2140. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2141. }
  2142. };
  2143. /**
  2144. * Returns the byte stride giving an accessor
  2145. * @param accessor: the GLTF accessor objet
  2146. */
  2147. GLTFUtils.GetByteStrideFromType = function (accessor) {
  2148. // Needs this function since "byteStride" isn't requiered in glTF format
  2149. var type = accessor.type;
  2150. switch (type) {
  2151. case "VEC2": return 2;
  2152. case "VEC3": return 3;
  2153. case "VEC4": return 4;
  2154. case "MAT2": return 4;
  2155. case "MAT3": return 9;
  2156. case "MAT4": return 16;
  2157. default: return 1;
  2158. }
  2159. };
  2160. /**
  2161. * Returns the texture filter mode giving a mode value
  2162. * @param mode: the filter mode value
  2163. */
  2164. GLTFUtils.GetTextureFilterMode = function (mode) {
  2165. switch (mode) {
  2166. case GLTF1.ETextureFilterType.LINEAR:
  2167. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  2168. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  2169. case GLTF1.ETextureFilterType.NEAREST:
  2170. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  2171. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  2172. }
  2173. };
  2174. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  2175. var byteOffset = bufferView.byteOffset + byteOffset;
  2176. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  2177. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  2178. throw new Error("Buffer access is out of range");
  2179. }
  2180. var buffer = loadedBufferView.buffer;
  2181. byteOffset += loadedBufferView.byteOffset;
  2182. switch (componentType) {
  2183. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  2184. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  2185. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  2186. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  2187. default: return new Float32Array(buffer, byteOffset, byteLength);
  2188. }
  2189. };
  2190. /**
  2191. * Returns a buffer from its accessor
  2192. * @param gltfRuntime: the GLTF runtime
  2193. * @param accessor: the GLTF accessor
  2194. */
  2195. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  2196. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  2197. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  2198. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  2199. };
  2200. /**
  2201. * Decodes a buffer view into a string
  2202. * @param view: the buffer view
  2203. */
  2204. GLTFUtils.DecodeBufferToText = function (view) {
  2205. var result = "";
  2206. var length = view.byteLength;
  2207. for (var i = 0; i < length; ++i) {
  2208. result += String.fromCharCode(view[i]);
  2209. }
  2210. return result;
  2211. };
  2212. /**
  2213. * Returns the default material of gltf. Related to
  2214. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  2215. * @param scene: the Babylon.js scene
  2216. */
  2217. GLTFUtils.GetDefaultMaterial = function (scene) {
  2218. if (!GLTFUtils._DefaultMaterial) {
  2219. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  2220. "precision highp float;",
  2221. "",
  2222. "uniform mat4 worldView;",
  2223. "uniform mat4 projection;",
  2224. "",
  2225. "attribute vec3 position;",
  2226. "",
  2227. "void main(void)",
  2228. "{",
  2229. " gl_Position = projection * worldView * vec4(position, 1.0);",
  2230. "}"
  2231. ].join("\n");
  2232. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  2233. "precision highp float;",
  2234. "",
  2235. "uniform vec4 u_emission;",
  2236. "",
  2237. "void main(void)",
  2238. "{",
  2239. " gl_FragColor = u_emission;",
  2240. "}"
  2241. ].join("\n");
  2242. var shaderPath = {
  2243. vertex: "GLTFDefaultMaterial",
  2244. fragment: "GLTFDefaultMaterial"
  2245. };
  2246. var options = {
  2247. attributes: ["position"],
  2248. uniforms: ["worldView", "projection", "u_emission"],
  2249. samplers: new Array(),
  2250. needAlphaBlending: false
  2251. };
  2252. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  2253. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  2254. }
  2255. return GLTFUtils._DefaultMaterial;
  2256. };
  2257. // The GLTF default material
  2258. GLTFUtils._DefaultMaterial = null;
  2259. return GLTFUtils;
  2260. }());
  2261. GLTF1.GLTFUtils = GLTFUtils;
  2262. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2263. })(BABYLON || (BABYLON = {}));
  2264. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  2265. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2266. var BABYLON;
  2267. (function (BABYLON) {
  2268. var GLTF1;
  2269. (function (GLTF1) {
  2270. var GLTFLoaderExtension = /** @class */ (function () {
  2271. function GLTFLoaderExtension(name) {
  2272. this._name = name;
  2273. }
  2274. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  2275. get: function () {
  2276. return this._name;
  2277. },
  2278. enumerable: true,
  2279. configurable: true
  2280. });
  2281. /**
  2282. * Defines an override for loading the runtime
  2283. * Return true to stop further extensions from loading the runtime
  2284. */
  2285. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2286. return false;
  2287. };
  2288. /**
  2289. * Defines an onverride for creating gltf runtime
  2290. * Return true to stop further extensions from creating the runtime
  2291. */
  2292. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2293. return false;
  2294. };
  2295. /**
  2296. * Defines an override for loading buffers
  2297. * Return true to stop further extensions from loading this buffer
  2298. */
  2299. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2300. return false;
  2301. };
  2302. /**
  2303. * Defines an override for loading texture buffers
  2304. * Return true to stop further extensions from loading this texture data
  2305. */
  2306. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2307. return false;
  2308. };
  2309. /**
  2310. * Defines an override for creating textures
  2311. * Return true to stop further extensions from loading this texture
  2312. */
  2313. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2314. return false;
  2315. };
  2316. /**
  2317. * Defines an override for loading shader strings
  2318. * Return true to stop further extensions from loading this shader data
  2319. */
  2320. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2321. return false;
  2322. };
  2323. /**
  2324. * Defines an override for loading materials
  2325. * Return true to stop further extensions from loading this material
  2326. */
  2327. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2328. return false;
  2329. };
  2330. // ---------
  2331. // Utilities
  2332. // ---------
  2333. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2334. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2335. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  2336. }, function () {
  2337. setTimeout(function () {
  2338. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2339. });
  2340. });
  2341. };
  2342. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2343. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2344. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  2345. }, function () {
  2346. setTimeout(function () {
  2347. onSuccess();
  2348. });
  2349. });
  2350. };
  2351. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2352. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2353. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2354. }, function () {
  2355. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2356. });
  2357. };
  2358. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  2359. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  2360. };
  2361. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2362. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2363. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2364. }, function () {
  2365. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2366. });
  2367. };
  2368. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2369. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2370. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2371. }, function () {
  2372. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2373. });
  2374. };
  2375. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2376. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2377. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2378. }, function () {
  2379. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2380. });
  2381. };
  2382. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2383. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2384. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2385. }, function () {
  2386. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2387. });
  2388. };
  2389. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  2390. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  2391. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  2392. if (func(loaderExtension)) {
  2393. return;
  2394. }
  2395. }
  2396. defaultFunc();
  2397. };
  2398. return GLTFLoaderExtension;
  2399. }());
  2400. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  2401. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2402. })(BABYLON || (BABYLON = {}));
  2403. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2404. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2405. var __extends = (this && this.__extends) || (function () {
  2406. var extendStatics = Object.setPrototypeOf ||
  2407. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2408. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2409. return function (d, b) {
  2410. extendStatics(d, b);
  2411. function __() { this.constructor = d; }
  2412. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2413. };
  2414. })();
  2415. var BABYLON;
  2416. (function (BABYLON) {
  2417. var GLTF1;
  2418. (function (GLTF1) {
  2419. var BinaryExtensionBufferName = "binary_glTF";
  2420. ;
  2421. ;
  2422. var GLTFBinaryExtension = /** @class */ (function (_super) {
  2423. __extends(GLTFBinaryExtension, _super);
  2424. function GLTFBinaryExtension() {
  2425. return _super.call(this, "KHR_binary_glTF") || this;
  2426. }
  2427. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2428. var extensionsUsed = data.json.extensionsUsed;
  2429. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  2430. return false;
  2431. }
  2432. this._bin = data.bin;
  2433. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2434. return true;
  2435. };
  2436. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2437. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  2438. return false;
  2439. }
  2440. if (id !== BinaryExtensionBufferName) {
  2441. return false;
  2442. }
  2443. onSuccess(this._bin);
  2444. return true;
  2445. };
  2446. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2447. var texture = gltfRuntime.textures[id];
  2448. var source = gltfRuntime.images[texture.source];
  2449. if (!source.extensions || !(this.name in source.extensions)) {
  2450. return false;
  2451. }
  2452. var sourceExt = source.extensions[this.name];
  2453. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  2454. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2455. onSuccess(buffer);
  2456. return true;
  2457. };
  2458. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2459. var shader = gltfRuntime.shaders[id];
  2460. if (!shader.extensions || !(this.name in shader.extensions)) {
  2461. return false;
  2462. }
  2463. var binaryExtensionShader = shader.extensions[this.name];
  2464. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  2465. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2466. setTimeout(function () {
  2467. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  2468. onSuccess(shaderString);
  2469. });
  2470. return true;
  2471. };
  2472. return GLTFBinaryExtension;
  2473. }(GLTF1.GLTFLoaderExtension));
  2474. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  2475. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  2476. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2477. })(BABYLON || (BABYLON = {}));
  2478. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  2479. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2480. var __extends = (this && this.__extends) || (function () {
  2481. var extendStatics = Object.setPrototypeOf ||
  2482. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2483. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2484. return function (d, b) {
  2485. extendStatics(d, b);
  2486. function __() { this.constructor = d; }
  2487. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2488. };
  2489. })();
  2490. var BABYLON;
  2491. (function (BABYLON) {
  2492. var GLTF1;
  2493. (function (GLTF1) {
  2494. ;
  2495. ;
  2496. ;
  2497. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  2498. __extends(GLTFMaterialsCommonExtension, _super);
  2499. function GLTFMaterialsCommonExtension() {
  2500. return _super.call(this, "KHR_materials_common") || this;
  2501. }
  2502. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2503. if (!gltfRuntime.extensions)
  2504. return false;
  2505. var extension = gltfRuntime.extensions[this.name];
  2506. if (!extension)
  2507. return false;
  2508. // Create lights
  2509. var lights = extension.lights;
  2510. if (lights) {
  2511. for (var thing in lights) {
  2512. var light = lights[thing];
  2513. switch (light.type) {
  2514. case "ambient":
  2515. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  2516. var ambient = light.ambient;
  2517. if (ambient) {
  2518. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  2519. }
  2520. break;
  2521. case "point":
  2522. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  2523. var point = light.point;
  2524. if (point) {
  2525. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  2526. }
  2527. break;
  2528. case "directional":
  2529. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  2530. var directional = light.directional;
  2531. if (directional) {
  2532. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  2533. }
  2534. break;
  2535. case "spot":
  2536. var spot = light.spot;
  2537. if (spot) {
  2538. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  2539. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  2540. }
  2541. break;
  2542. default:
  2543. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  2544. break;
  2545. }
  2546. }
  2547. }
  2548. return false;
  2549. };
  2550. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2551. var material = gltfRuntime.materials[id];
  2552. if (!material || !material.extensions)
  2553. return false;
  2554. var extension = material.extensions[this.name];
  2555. if (!extension)
  2556. return false;
  2557. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2558. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2559. if (extension.technique === "CONSTANT") {
  2560. standardMaterial.disableLighting = true;
  2561. }
  2562. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2563. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2564. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2565. // Ambient
  2566. if (typeof extension.values.ambient === "string") {
  2567. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2568. }
  2569. else {
  2570. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2571. }
  2572. // Diffuse
  2573. if (typeof extension.values.diffuse === "string") {
  2574. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2575. }
  2576. else {
  2577. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2578. }
  2579. // Emission
  2580. if (typeof extension.values.emission === "string") {
  2581. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2582. }
  2583. else {
  2584. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2585. }
  2586. // Specular
  2587. if (typeof extension.values.specular === "string") {
  2588. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2589. }
  2590. else {
  2591. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2592. }
  2593. return true;
  2594. };
  2595. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2596. // Create buffer from texture url
  2597. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2598. // Create texture from buffer
  2599. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2600. }, onError);
  2601. };
  2602. return GLTFMaterialsCommonExtension;
  2603. }(GLTF1.GLTFLoaderExtension));
  2604. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  2605. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  2606. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2607. })(BABYLON || (BABYLON = {}));
  2608. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  2609. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2610. var BABYLON;
  2611. (function (BABYLON) {
  2612. var GLTF2;
  2613. (function (GLTF2) {
  2614. var ArrayItem = /** @class */ (function () {
  2615. function ArrayItem() {
  2616. }
  2617. ArrayItem.Assign = function (values) {
  2618. if (values) {
  2619. for (var index = 0; index < values.length; index++) {
  2620. values[index]._index = index;
  2621. }
  2622. }
  2623. };
  2624. return ArrayItem;
  2625. }());
  2626. GLTF2.ArrayItem = ArrayItem;
  2627. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2628. })(BABYLON || (BABYLON = {}));
  2629. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  2630. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2631. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  2632. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  2633. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2634. var BABYLON;
  2635. (function (BABYLON) {
  2636. var GLTF2;
  2637. (function (GLTF2) {
  2638. var GLTFLoader = /** @class */ (function () {
  2639. function GLTFLoader() {
  2640. this._completePromises = new Array();
  2641. this._disposed = false;
  2642. this._state = null;
  2643. this._extensions = {};
  2644. this._defaultSampler = {};
  2645. this._requests = new Array();
  2646. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  2647. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  2648. this.compileMaterials = false;
  2649. this.useClipPlane = false;
  2650. this.compileShadowGenerators = false;
  2651. this.onDisposeObservable = new BABYLON.Observable();
  2652. this.onMeshLoadedObservable = new BABYLON.Observable();
  2653. this.onTextureLoadedObservable = new BABYLON.Observable();
  2654. this.onMaterialLoadedObservable = new BABYLON.Observable();
  2655. this.onExtensionLoadedObservable = new BABYLON.Observable();
  2656. this.onCompleteObservable = new BABYLON.Observable();
  2657. }
  2658. GLTFLoader._Register = function (name, factory) {
  2659. if (GLTFLoader._Factories[name]) {
  2660. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  2661. return;
  2662. }
  2663. GLTFLoader._Factories[name] = factory;
  2664. // Keep the order of registration so that extensions registered first are called first.
  2665. GLTFLoader._Names.push(name);
  2666. };
  2667. Object.defineProperty(GLTFLoader.prototype, "state", {
  2668. get: function () {
  2669. return this._state;
  2670. },
  2671. enumerable: true,
  2672. configurable: true
  2673. });
  2674. GLTFLoader.prototype.dispose = function () {
  2675. if (this._disposed) {
  2676. return;
  2677. }
  2678. this._disposed = true;
  2679. this._abortRequests();
  2680. this._releaseResources();
  2681. this.onDisposeObservable.notifyObservers(this);
  2682. };
  2683. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  2684. var _this = this;
  2685. return Promise.resolve().then(function () {
  2686. var nodes = null;
  2687. if (meshesNames) {
  2688. var nodeMap_1 = {};
  2689. if (_this._gltf.nodes) {
  2690. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  2691. var node = _a[_i];
  2692. if (node.name) {
  2693. nodeMap_1[node.name] = node;
  2694. }
  2695. }
  2696. }
  2697. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  2698. nodes = names.map(function (name) {
  2699. var node = nodeMap_1[name];
  2700. if (!node) {
  2701. throw new Error("Failed to find node " + name);
  2702. }
  2703. return node;
  2704. });
  2705. }
  2706. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  2707. return {
  2708. meshes: _this._getMeshes(),
  2709. particleSystems: [],
  2710. skeletons: _this._getSkeletons(),
  2711. };
  2712. });
  2713. });
  2714. };
  2715. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  2716. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  2717. };
  2718. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  2719. var _this = this;
  2720. return Promise.resolve().then(function () {
  2721. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  2722. var name_1 = _a[_i];
  2723. var extension = GLTFLoader._Factories[name_1](_this);
  2724. _this._extensions[name_1] = extension;
  2725. _this.onExtensionLoadedObservable.notifyObservers(extension);
  2726. }
  2727. _this._babylonScene = scene;
  2728. _this._rootUrl = rootUrl;
  2729. _this._progressCallback = onProgress;
  2730. _this._state = BABYLON.GLTFLoaderState.Loading;
  2731. _this._loadData(data);
  2732. var promises = new Array();
  2733. if (nodes) {
  2734. promises.push(_this._loadNodesAsync(nodes));
  2735. }
  2736. else {
  2737. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  2738. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  2739. }
  2740. if (_this.compileMaterials) {
  2741. promises.push(_this._compileMaterialsAsync());
  2742. }
  2743. if (_this.compileShadowGenerators) {
  2744. promises.push(_this._compileShadowGeneratorsAsync());
  2745. }
  2746. return Promise.all(promises).then(function () {
  2747. _this._state = BABYLON.GLTFLoaderState.Ready;
  2748. _this._startAnimations();
  2749. BABYLON.Tools.SetImmediate(function () {
  2750. if (!_this._disposed) {
  2751. Promise.all(_this._completePromises).then(function () {
  2752. _this._releaseResources();
  2753. _this._state = BABYLON.GLTFLoaderState.Complete;
  2754. _this.onCompleteObservable.notifyObservers(_this);
  2755. }).catch(function (error) {
  2756. BABYLON.Tools.Error("glTF Loader: " + error.message);
  2757. _this.dispose();
  2758. });
  2759. }
  2760. });
  2761. });
  2762. }).catch(function (error) {
  2763. BABYLON.Tools.Error("glTF Loader: " + error.message);
  2764. _this.dispose();
  2765. throw error;
  2766. });
  2767. };
  2768. GLTFLoader.prototype._loadData = function (data) {
  2769. this._gltf = data.json;
  2770. this._setupData();
  2771. if (data.bin) {
  2772. var buffers = this._gltf.buffers;
  2773. if (buffers && buffers[0] && !buffers[0].uri) {
  2774. var binaryBuffer = buffers[0];
  2775. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  2776. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  2777. }
  2778. binaryBuffer._data = Promise.resolve(data.bin);
  2779. }
  2780. else {
  2781. BABYLON.Tools.Warn("Unexpected BIN chunk");
  2782. }
  2783. }
  2784. };
  2785. GLTFLoader.prototype._setupData = function () {
  2786. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  2787. GLTF2.ArrayItem.Assign(this._gltf.animations);
  2788. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  2789. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  2790. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  2791. GLTF2.ArrayItem.Assign(this._gltf.images);
  2792. GLTF2.ArrayItem.Assign(this._gltf.materials);
  2793. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  2794. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  2795. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  2796. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  2797. GLTF2.ArrayItem.Assign(this._gltf.skins);
  2798. GLTF2.ArrayItem.Assign(this._gltf.textures);
  2799. if (this._gltf.nodes) {
  2800. var nodeParents = {};
  2801. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  2802. var node = _a[_i];
  2803. if (node.children) {
  2804. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  2805. var index = _c[_b];
  2806. nodeParents[index] = node._index;
  2807. }
  2808. }
  2809. }
  2810. var rootNode = this._createRootNode();
  2811. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  2812. var node = _e[_d];
  2813. var parentIndex = nodeParents[node._index];
  2814. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  2815. }
  2816. }
  2817. };
  2818. GLTFLoader.prototype._createRootNode = function () {
  2819. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  2820. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  2821. switch (this.coordinateSystemMode) {
  2822. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  2823. if (!this._babylonScene.useRightHandedSystem) {
  2824. rootNode.rotation = [0, 1, 0, 0];
  2825. rootNode.scale = [1, 1, -1];
  2826. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  2827. }
  2828. break;
  2829. }
  2830. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  2831. this._babylonScene.useRightHandedSystem = true;
  2832. break;
  2833. }
  2834. default: {
  2835. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  2836. }
  2837. }
  2838. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  2839. return rootNode;
  2840. };
  2841. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  2842. var promises = new Array();
  2843. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  2844. var node = nodes_1[_i];
  2845. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  2846. }
  2847. promises.push(this._loadAnimationsAsync());
  2848. return Promise.all(promises).then(function () { });
  2849. };
  2850. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  2851. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  2852. if (promise) {
  2853. return promise;
  2854. }
  2855. var promises = new Array();
  2856. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  2857. var index = _a[_i];
  2858. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  2859. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  2860. }
  2861. promises.push(this._loadAnimationsAsync());
  2862. return Promise.all(promises).then(function () { });
  2863. };
  2864. GLTFLoader.prototype._getMeshes = function () {
  2865. var meshes = new Array();
  2866. // Root mesh is always first.
  2867. meshes.push(this._rootBabylonMesh);
  2868. var nodes = this._gltf.nodes;
  2869. if (nodes) {
  2870. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  2871. var node = nodes_2[_i];
  2872. if (node._babylonMesh) {
  2873. meshes.push(node._babylonMesh);
  2874. }
  2875. }
  2876. }
  2877. return meshes;
  2878. };
  2879. GLTFLoader.prototype._getSkeletons = function () {
  2880. var skeletons = new Array();
  2881. var skins = this._gltf.skins;
  2882. if (skins) {
  2883. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  2884. var skin = skins_1[_i];
  2885. if (skin._babylonSkeleton) {
  2886. skeletons.push(skin._babylonSkeleton);
  2887. }
  2888. }
  2889. }
  2890. return skeletons;
  2891. };
  2892. GLTFLoader.prototype._startAnimations = function () {
  2893. var animations = this._gltf.animations;
  2894. if (!animations) {
  2895. return;
  2896. }
  2897. switch (this.animationStartMode) {
  2898. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  2899. // do nothing
  2900. break;
  2901. }
  2902. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  2903. var animation = animations[0];
  2904. animation._babylonAnimationGroup.start(true);
  2905. break;
  2906. }
  2907. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  2908. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  2909. var animation = animations_1[_i];
  2910. animation._babylonAnimationGroup.start(true);
  2911. }
  2912. break;
  2913. }
  2914. default: {
  2915. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  2916. return;
  2917. }
  2918. }
  2919. };
  2920. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  2921. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  2922. if (promise) {
  2923. return promise;
  2924. }
  2925. if (node._babylonMesh) {
  2926. throw new Error(context + ": Invalid recursive node hierarchy");
  2927. }
  2928. var promises = new Array();
  2929. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  2930. node._babylonMesh = babylonMesh;
  2931. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  2932. node._babylonAnimationTargets.push(babylonMesh);
  2933. GLTFLoader._LoadTransform(node, babylonMesh);
  2934. if (node.mesh != undefined) {
  2935. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  2936. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  2937. }
  2938. if (node.children) {
  2939. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  2940. var index = _a[_i];
  2941. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  2942. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  2943. }
  2944. }
  2945. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  2946. return Promise.all(promises).then(function () { });
  2947. };
  2948. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  2949. // TODO: instancing
  2950. var promises = new Array();
  2951. var primitives = mesh.primitives;
  2952. if (!primitives || primitives.length === 0) {
  2953. throw new Error(context + ": Primitives are missing");
  2954. }
  2955. GLTF2.ArrayItem.Assign(primitives);
  2956. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  2957. var primitive = primitives_1[_i];
  2958. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  2959. }
  2960. if (node.skin != undefined) {
  2961. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  2962. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  2963. }
  2964. return Promise.all(promises).then(function () {
  2965. if (node._primitiveBabylonMeshes) {
  2966. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  2967. var primitiveBabylonMesh = _a[_i];
  2968. primitiveBabylonMesh._refreshBoundingInfo(true);
  2969. }
  2970. }
  2971. });
  2972. };
  2973. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  2974. var _this = this;
  2975. var promises = new Array();
  2976. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  2977. babylonMesh.setEnabled(false);
  2978. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  2979. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  2980. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  2981. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  2982. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  2983. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  2984. }));
  2985. if (primitive.material == undefined) {
  2986. babylonMesh.material = this._getDefaultMaterial();
  2987. }
  2988. else {
  2989. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  2990. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  2991. }
  2992. return Promise.all(promises).then(function () {
  2993. babylonMesh.setEnabled(true);
  2994. });
  2995. };
  2996. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  2997. var _this = this;
  2998. var attributes = primitive.attributes;
  2999. if (!attributes) {
  3000. throw new Error(context + ": Attributes are missing");
  3001. }
  3002. if (primitive.mode && primitive.mode !== 4 /* TRIANGLES */) {
  3003. // TODO: handle other primitive modes
  3004. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  3005. }
  3006. var promises = new Array();
  3007. var babylonVertexData = new BABYLON.VertexData();
  3008. if (primitive.indices == undefined) {
  3009. var positionAccessorIndex = attributes["POSITION"];
  3010. if (positionAccessorIndex != undefined) {
  3011. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  3012. babylonVertexData.indices = new Uint32Array(accessor.count);
  3013. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  3014. babylonVertexData.indices[i] = i;
  3015. }
  3016. }
  3017. }
  3018. else {
  3019. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  3020. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  3021. babylonVertexData.indices = data;
  3022. }));
  3023. }
  3024. var loadAttribute = function (attribute, kind) {
  3025. if (attributes[attribute] == undefined) {
  3026. return;
  3027. }
  3028. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  3029. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  3030. babylonMesh._delayInfo.push(kind);
  3031. }
  3032. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  3033. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  3034. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  3035. if (attribute === "COLOR_0") {
  3036. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  3037. babylonMesh.hasVertexAlpha = true;
  3038. if (accessor.type === "VEC3") {
  3039. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  3040. }
  3041. }
  3042. babylonVertexData.set(attributeData, kind);
  3043. }));
  3044. };
  3045. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  3046. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  3047. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  3048. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  3049. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  3050. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  3051. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  3052. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  3053. return Promise.all(promises).then(function () {
  3054. return babylonVertexData;
  3055. });
  3056. };
  3057. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  3058. if (!primitive.targets) {
  3059. return;
  3060. }
  3061. if (node._numMorphTargets == undefined) {
  3062. node._numMorphTargets = primitive.targets.length;
  3063. }
  3064. else if (primitive.targets.length !== node._numMorphTargets) {
  3065. throw new Error(context + ": Primitives do not have the same number of targets");
  3066. }
  3067. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  3068. for (var index = 0; index < primitive.targets.length; index++) {
  3069. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  3070. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  3071. // TODO: tell the target whether it has positions, normals, tangents
  3072. }
  3073. };
  3074. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  3075. if (!primitive.targets) {
  3076. return Promise.resolve();
  3077. }
  3078. var promises = new Array();
  3079. var morphTargetManager = babylonMesh.morphTargetManager;
  3080. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  3081. var babylonMorphTarget = morphTargetManager.getTarget(index);
  3082. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  3083. }
  3084. return Promise.all(promises).then(function () { });
  3085. };
  3086. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  3087. var _this = this;
  3088. var promises = new Array();
  3089. var loadAttribute = function (attribute, setData) {
  3090. if (attributes[attribute] == undefined) {
  3091. return;
  3092. }
  3093. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  3094. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  3095. setData(data);
  3096. }));
  3097. };
  3098. loadAttribute("POSITION", function (data) {
  3099. if (babylonVertexData.positions) {
  3100. for (var i = 0; i < data.length; i++) {
  3101. data[i] += babylonVertexData.positions[i];
  3102. }
  3103. babylonMorphTarget.setPositions(data);
  3104. }
  3105. });
  3106. loadAttribute("NORMAL", function (data) {
  3107. if (babylonVertexData.normals) {
  3108. for (var i = 0; i < data.length; i++) {
  3109. data[i] += babylonVertexData.normals[i];
  3110. }
  3111. babylonMorphTarget.setNormals(data);
  3112. }
  3113. });
  3114. loadAttribute("TANGENT", function (data) {
  3115. if (babylonVertexData.tangents) {
  3116. // Tangent data for morph targets is stored as xyz delta.
  3117. // The vertexData.tangent is stored as xyzw.
  3118. // So we need to skip every fourth vertexData.tangent.
  3119. for (var i = 0, j = 0; i < data.length; i++) {
  3120. data[i] += babylonVertexData.tangents[j++];
  3121. if ((i + 1) % 3 == 0) {
  3122. j++;
  3123. }
  3124. }
  3125. babylonMorphTarget.setTangents(data);
  3126. }
  3127. });
  3128. return Promise.all(promises).then(function () { });
  3129. };
  3130. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  3131. if (accessor.componentType == 5126 /* FLOAT */) {
  3132. return data;
  3133. }
  3134. var factor = 1;
  3135. if (accessor.normalized) {
  3136. switch (accessor.componentType) {
  3137. case 5121 /* UNSIGNED_BYTE */: {
  3138. factor = 1 / 255;
  3139. break;
  3140. }
  3141. case 5123 /* UNSIGNED_SHORT */: {
  3142. factor = 1 / 65535;
  3143. break;
  3144. }
  3145. default: {
  3146. throw new Error(context + ": Invalid component type " + accessor.componentType);
  3147. }
  3148. }
  3149. }
  3150. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  3151. for (var i = 0; i < result.length; i++) {
  3152. result[i] = data[i] * factor;
  3153. }
  3154. return result;
  3155. };
  3156. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  3157. var result = new Float32Array(data.length / 3 * 4);
  3158. var offset = 0;
  3159. for (var i = 0; i < result.length; i++) {
  3160. if ((i + 1) % 4 === 0) {
  3161. result[i] = 1;
  3162. }
  3163. else {
  3164. result[i] = data[offset++];
  3165. }
  3166. }
  3167. return result;
  3168. };
  3169. GLTFLoader._LoadTransform = function (node, babylonNode) {
  3170. var position = BABYLON.Vector3.Zero();
  3171. var rotation = BABYLON.Quaternion.Identity();
  3172. var scaling = BABYLON.Vector3.One();
  3173. if (node.matrix) {
  3174. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  3175. matrix.decompose(scaling, rotation, position);
  3176. }
  3177. else {
  3178. if (node.translation)
  3179. position = BABYLON.Vector3.FromArray(node.translation);
  3180. if (node.rotation)
  3181. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  3182. if (node.scale)
  3183. scaling = BABYLON.Vector3.FromArray(node.scale);
  3184. }
  3185. babylonNode.position = position;
  3186. babylonNode.rotationQuaternion = rotation;
  3187. babylonNode.scaling = scaling;
  3188. };
  3189. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  3190. var _this = this;
  3191. var assignSkeleton = function () {
  3192. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  3193. var babylonMesh = _a[_i];
  3194. babylonMesh.skeleton = skin._babylonSkeleton;
  3195. }
  3196. node._babylonMesh.parent = _this._rootBabylonMesh;
  3197. node._babylonMesh.position = BABYLON.Vector3.Zero();
  3198. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  3199. node._babylonMesh.scaling = BABYLON.Vector3.One();
  3200. };
  3201. if (skin._loaded) {
  3202. assignSkeleton();
  3203. return skin._loaded;
  3204. }
  3205. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  3206. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  3207. var skeletonId = "skeleton" + skin._index;
  3208. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  3209. skin._babylonSkeleton = babylonSkeleton;
  3210. _this._loadBones(context, skin, inverseBindMatricesData);
  3211. assignSkeleton();
  3212. }));
  3213. };
  3214. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  3215. if (skin.inverseBindMatrices == undefined) {
  3216. return Promise.resolve(null);
  3217. }
  3218. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  3219. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  3220. return data;
  3221. });
  3222. };
  3223. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  3224. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  3225. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  3226. node._babylonAnimationTargets.push(babylonBone);
  3227. return babylonBone;
  3228. };
  3229. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  3230. var babylonBones = {};
  3231. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  3232. var index = _a[_i];
  3233. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  3234. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  3235. }
  3236. };
  3237. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  3238. var babylonBone = babylonBones[node._index];
  3239. if (babylonBone) {
  3240. return babylonBone;
  3241. }
  3242. var boneIndex = skin.joints.indexOf(node._index);
  3243. var baseMatrix = BABYLON.Matrix.Identity();
  3244. if (inverseBindMatricesData && boneIndex !== -1) {
  3245. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  3246. baseMatrix.invertToRef(baseMatrix);
  3247. }
  3248. var babylonParentBone = null;
  3249. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  3250. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  3251. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  3252. }
  3253. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  3254. babylonBones[node._index] = babylonBone;
  3255. return babylonBone;
  3256. };
  3257. GLTFLoader.prototype._getNodeMatrix = function (node) {
  3258. return node.matrix ?
  3259. BABYLON.Matrix.FromArray(node.matrix) :
  3260. 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());
  3261. };
  3262. GLTFLoader.prototype._loadAnimationsAsync = function () {
  3263. var animations = this._gltf.animations;
  3264. if (!animations) {
  3265. return Promise.resolve();
  3266. }
  3267. var promises = new Array();
  3268. for (var index = 0; index < animations.length; index++) {
  3269. var animation = animations[index];
  3270. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  3271. }
  3272. return Promise.all(promises).then(function () { });
  3273. };
  3274. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  3275. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  3276. animation._babylonAnimationGroup = babylonAnimationGroup;
  3277. var promises = new Array();
  3278. GLTF2.ArrayItem.Assign(animation.channels);
  3279. GLTF2.ArrayItem.Assign(animation.samplers);
  3280. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  3281. var channel = _a[_i];
  3282. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  3283. }
  3284. return Promise.all(promises).then(function () {
  3285. babylonAnimationGroup.normalize();
  3286. });
  3287. };
  3288. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  3289. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  3290. if (!targetNode._babylonMesh) {
  3291. return Promise.resolve();
  3292. }
  3293. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  3294. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  3295. var targetPath;
  3296. var animationType;
  3297. switch (channel.target.path) {
  3298. case "translation" /* TRANSLATION */: {
  3299. targetPath = "position";
  3300. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  3301. break;
  3302. }
  3303. case "rotation" /* ROTATION */: {
  3304. targetPath = "rotationQuaternion";
  3305. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  3306. break;
  3307. }
  3308. case "scale" /* SCALE */: {
  3309. targetPath = "scaling";
  3310. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  3311. break;
  3312. }
  3313. case "weights" /* WEIGHTS */: {
  3314. targetPath = "influence";
  3315. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  3316. break;
  3317. }
  3318. default: {
  3319. throw new Error(context + ": Invalid target path " + channel.target.path);
  3320. }
  3321. }
  3322. var outputBufferOffset = 0;
  3323. var getNextOutputValue;
  3324. switch (targetPath) {
  3325. case "position": {
  3326. getNextOutputValue = function () {
  3327. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  3328. outputBufferOffset += 3;
  3329. return value;
  3330. };
  3331. break;
  3332. }
  3333. case "rotationQuaternion": {
  3334. getNextOutputValue = function () {
  3335. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  3336. outputBufferOffset += 4;
  3337. return value;
  3338. };
  3339. break;
  3340. }
  3341. case "scaling": {
  3342. getNextOutputValue = function () {
  3343. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  3344. outputBufferOffset += 3;
  3345. return value;
  3346. };
  3347. break;
  3348. }
  3349. case "influence": {
  3350. getNextOutputValue = function () {
  3351. var value = new Array(targetNode._numMorphTargets);
  3352. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  3353. value[i] = data.output[outputBufferOffset++];
  3354. }
  3355. return value;
  3356. };
  3357. break;
  3358. }
  3359. }
  3360. var getNextKey;
  3361. switch (data.interpolation) {
  3362. case "STEP" /* STEP */: {
  3363. getNextKey = function (frameIndex) { return ({
  3364. frame: data.input[frameIndex],
  3365. value: getNextOutputValue(),
  3366. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  3367. }); };
  3368. break;
  3369. }
  3370. case "LINEAR" /* LINEAR */: {
  3371. getNextKey = function (frameIndex) { return ({
  3372. frame: data.input[frameIndex],
  3373. value: getNextOutputValue()
  3374. }); };
  3375. break;
  3376. }
  3377. case "CUBICSPLINE" /* CUBICSPLINE */: {
  3378. getNextKey = function (frameIndex) { return ({
  3379. frame: data.input[frameIndex],
  3380. inTangent: getNextOutputValue(),
  3381. value: getNextOutputValue(),
  3382. outTangent: getNextOutputValue()
  3383. }); };
  3384. break;
  3385. }
  3386. }
  3387. var keys;
  3388. if (data.input.length === 1) {
  3389. var key = getNextKey(0);
  3390. keys = [
  3391. { frame: key.frame, value: key.value },
  3392. { frame: key.frame + 1, value: key.value }
  3393. ];
  3394. }
  3395. else {
  3396. keys = new Array(data.input.length);
  3397. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  3398. keys[frameIndex] = getNextKey(frameIndex);
  3399. }
  3400. }
  3401. if (targetPath === "influence") {
  3402. var _loop_1 = function (targetIndex) {
  3403. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  3404. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  3405. babylonAnimation.setKeys(keys.map(function (key) { return ({
  3406. frame: key.frame,
  3407. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  3408. value: key.value[targetIndex],
  3409. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  3410. }); }));
  3411. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  3412. var babylonMesh = _a[_i];
  3413. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  3414. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  3415. }
  3416. };
  3417. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  3418. _loop_1(targetIndex);
  3419. }
  3420. }
  3421. else {
  3422. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  3423. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  3424. babylonAnimation.setKeys(keys);
  3425. if (targetNode._babylonAnimationTargets) {
  3426. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  3427. var target = _a[_i];
  3428. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  3429. }
  3430. }
  3431. }
  3432. });
  3433. };
  3434. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  3435. if (sampler._data) {
  3436. return sampler._data;
  3437. }
  3438. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  3439. switch (interpolation) {
  3440. case "STEP" /* STEP */:
  3441. case "LINEAR" /* LINEAR */:
  3442. case "CUBICSPLINE" /* CUBICSPLINE */: {
  3443. break;
  3444. }
  3445. default: {
  3446. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  3447. }
  3448. }
  3449. var inputData;
  3450. var outputData;
  3451. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  3452. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  3453. sampler._data = Promise.all([
  3454. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  3455. inputData = data;
  3456. }),
  3457. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  3458. outputData = data;
  3459. })
  3460. ]).then(function () {
  3461. return {
  3462. input: inputData,
  3463. interpolation: interpolation,
  3464. output: outputData,
  3465. };
  3466. });
  3467. return sampler._data;
  3468. };
  3469. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  3470. if (buffer._data) {
  3471. return buffer._data;
  3472. }
  3473. if (!buffer.uri) {
  3474. throw new Error(context + ": Uri is missing");
  3475. }
  3476. buffer._data = this._loadUriAsync(context, buffer.uri);
  3477. return buffer._data;
  3478. };
  3479. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  3480. if (bufferView._data) {
  3481. return bufferView._data;
  3482. }
  3483. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  3484. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  3485. try {
  3486. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  3487. }
  3488. catch (e) {
  3489. throw new Error(context + ": " + e.message);
  3490. }
  3491. });
  3492. return bufferView._data;
  3493. };
  3494. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  3495. var _this = this;
  3496. if (accessor.sparse) {
  3497. throw new Error(context + ": Sparse accessors are not currently supported");
  3498. }
  3499. if (accessor._data) {
  3500. return accessor._data;
  3501. }
  3502. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  3503. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  3504. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  3505. var byteOffset = accessor.byteOffset || 0;
  3506. var byteStride = bufferView.byteStride;
  3507. if (byteStride === 0) {
  3508. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  3509. }
  3510. try {
  3511. switch (accessor.componentType) {
  3512. case 5120 /* BYTE */: {
  3513. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3514. }
  3515. case 5121 /* UNSIGNED_BYTE */: {
  3516. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3517. }
  3518. case 5122 /* SHORT */: {
  3519. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3520. }
  3521. case 5123 /* UNSIGNED_SHORT */: {
  3522. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3523. }
  3524. case 5125 /* UNSIGNED_INT */: {
  3525. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3526. }
  3527. case 5126 /* FLOAT */: {
  3528. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3529. }
  3530. default: {
  3531. throw new Error(context + ": Invalid component type " + accessor.componentType);
  3532. }
  3533. }
  3534. }
  3535. catch (e) {
  3536. throw new Error(context + ": " + e);
  3537. }
  3538. });
  3539. return accessor._data;
  3540. };
  3541. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  3542. byteOffset += data.byteOffset;
  3543. var targetLength = count * numComponents;
  3544. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  3545. return new typedArray(data.buffer, byteOffset, targetLength);
  3546. }
  3547. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  3548. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  3549. var targetBuffer = new typedArray(targetLength);
  3550. var sourceIndex = 0;
  3551. var targetIndex = 0;
  3552. while (targetIndex < targetLength) {
  3553. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  3554. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  3555. targetIndex++;
  3556. }
  3557. sourceIndex += elementStride;
  3558. }
  3559. return targetBuffer;
  3560. };
  3561. GLTFLoader.prototype._getDefaultMaterial = function () {
  3562. var id = "__gltf_default";
  3563. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  3564. if (!babylonMaterial) {
  3565. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  3566. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  3567. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  3568. babylonMaterial.metallic = 1;
  3569. babylonMaterial.roughness = 1;
  3570. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  3571. }
  3572. return babylonMaterial;
  3573. };
  3574. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  3575. var promises = new Array();
  3576. var babylonMaterial = material._babylonMaterial;
  3577. // Ensure metallic workflow
  3578. babylonMaterial.metallic = 1;
  3579. babylonMaterial.roughness = 1;
  3580. var properties = material.pbrMetallicRoughness;
  3581. if (properties) {
  3582. if (properties.baseColorFactor) {
  3583. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  3584. babylonMaterial.alpha = properties.baseColorFactor[3];
  3585. }
  3586. else {
  3587. babylonMaterial.albedoColor = BABYLON.Color3.White();
  3588. }
  3589. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  3590. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  3591. if (properties.baseColorTexture) {
  3592. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  3593. babylonMaterial.albedoTexture = texture;
  3594. }));
  3595. }
  3596. if (properties.metallicRoughnessTexture) {
  3597. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  3598. babylonMaterial.metallicTexture = texture;
  3599. }));
  3600. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  3601. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  3602. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  3603. }
  3604. }
  3605. this._loadMaterialAlphaProperties(context, material);
  3606. return Promise.all(promises).then(function () { });
  3607. };
  3608. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  3609. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  3610. if (promise) {
  3611. return promise;
  3612. }
  3613. material._babylonMeshes = material._babylonMeshes || [];
  3614. material._babylonMeshes.push(babylonMesh);
  3615. if (material._loaded) {
  3616. babylonMesh.material = material._babylonMaterial;
  3617. return material._loaded;
  3618. }
  3619. var promises = new Array();
  3620. var babylonMaterial = this._createMaterial(material);
  3621. material._babylonMaterial = babylonMaterial;
  3622. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  3623. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  3624. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  3625. babylonMesh.material = babylonMaterial;
  3626. return (material._loaded = Promise.all(promises).then(function () { }));
  3627. };
  3628. GLTFLoader.prototype._createMaterial = function (material) {
  3629. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  3630. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  3631. return babylonMaterial;
  3632. };
  3633. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  3634. var promises = new Array();
  3635. var babylonMaterial = material._babylonMaterial;
  3636. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  3637. if (material.doubleSided) {
  3638. babylonMaterial.backFaceCulling = false;
  3639. babylonMaterial.twoSidedLighting = true;
  3640. }
  3641. if (material.normalTexture) {
  3642. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  3643. babylonMaterial.bumpTexture = texture;
  3644. }));
  3645. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  3646. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  3647. if (material.normalTexture.scale != undefined) {
  3648. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  3649. }
  3650. }
  3651. if (material.occlusionTexture) {
  3652. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  3653. babylonMaterial.ambientTexture = texture;
  3654. }));
  3655. babylonMaterial.useAmbientInGrayScale = true;
  3656. if (material.occlusionTexture.strength != undefined) {
  3657. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  3658. }
  3659. }
  3660. if (material.emissiveTexture) {
  3661. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  3662. babylonMaterial.emissiveTexture = texture;
  3663. }));
  3664. }
  3665. return Promise.all(promises).then(function () { });
  3666. };
  3667. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  3668. var babylonMaterial = material._babylonMaterial;
  3669. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  3670. switch (alphaMode) {
  3671. case "OPAQUE" /* OPAQUE */: {
  3672. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  3673. break;
  3674. }
  3675. case "MASK" /* MASK */: {
  3676. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  3677. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  3678. if (babylonMaterial.alpha) {
  3679. if (babylonMaterial.alpha === 0) {
  3680. babylonMaterial.alphaCutOff = 1;
  3681. }
  3682. else {
  3683. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  3684. }
  3685. babylonMaterial.alpha = 1;
  3686. }
  3687. if (babylonMaterial.albedoTexture) {
  3688. babylonMaterial.albedoTexture.hasAlpha = true;
  3689. }
  3690. break;
  3691. }
  3692. case "BLEND" /* BLEND */: {
  3693. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  3694. if (babylonMaterial.albedoTexture) {
  3695. babylonMaterial.albedoTexture.hasAlpha = true;
  3696. babylonMaterial.useAlphaFromAlbedoTexture = true;
  3697. }
  3698. break;
  3699. }
  3700. default: {
  3701. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  3702. }
  3703. }
  3704. };
  3705. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  3706. var _this = this;
  3707. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  3708. context = "#/textures/" + textureInfo.index;
  3709. var promises = new Array();
  3710. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  3711. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  3712. var deferred = new BABYLON.Deferred();
  3713. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  3714. if (!_this._disposed) {
  3715. deferred.resolve();
  3716. }
  3717. }, function (message, exception) {
  3718. if (!_this._disposed) {
  3719. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  3720. }
  3721. });
  3722. promises.push(deferred.promise);
  3723. babylonTexture.name = texture.name || "texture" + texture._index;
  3724. babylonTexture.wrapU = samplerData.wrapU;
  3725. babylonTexture.wrapV = samplerData.wrapV;
  3726. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  3727. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  3728. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  3729. babylonTexture.updateURL(objectURL);
  3730. }));
  3731. assign(babylonTexture);
  3732. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  3733. return Promise.all(promises).then(function () { });
  3734. };
  3735. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  3736. if (!sampler._data) {
  3737. sampler._data = {
  3738. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  3739. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  3740. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  3741. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  3742. };
  3743. }
  3744. ;
  3745. return sampler._data;
  3746. };
  3747. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  3748. if (image._objectURL) {
  3749. return image._objectURL;
  3750. }
  3751. var promise;
  3752. if (image.uri) {
  3753. promise = this._loadUriAsync(context, image.uri);
  3754. }
  3755. else {
  3756. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  3757. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  3758. }
  3759. image._objectURL = promise.then(function (data) {
  3760. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  3761. });
  3762. return image._objectURL;
  3763. };
  3764. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  3765. var _this = this;
  3766. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  3767. if (promise) {
  3768. return promise;
  3769. }
  3770. if (!GLTFLoader._ValidateUri(uri)) {
  3771. throw new Error(context + ": Uri '" + uri + "' is invalid");
  3772. }
  3773. if (BABYLON.Tools.IsBase64(uri)) {
  3774. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  3775. }
  3776. return new Promise(function (resolve, reject) {
  3777. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  3778. if (!_this._disposed) {
  3779. resolve(new Uint8Array(data));
  3780. }
  3781. }, function (event) {
  3782. if (!_this._disposed) {
  3783. try {
  3784. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  3785. request._lengthComputable = event.lengthComputable;
  3786. request._loaded = event.loaded;
  3787. request._total = event.total;
  3788. _this._onProgress();
  3789. }
  3790. }
  3791. catch (e) {
  3792. reject(e);
  3793. }
  3794. }
  3795. }, _this._babylonScene.database, true, function (request, exception) {
  3796. if (!_this._disposed) {
  3797. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  3798. }
  3799. });
  3800. _this._requests.push(request);
  3801. });
  3802. };
  3803. GLTFLoader.prototype._onProgress = function () {
  3804. if (!this._progressCallback) {
  3805. return;
  3806. }
  3807. var lengthComputable = true;
  3808. var loaded = 0;
  3809. var total = 0;
  3810. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  3811. var request = _a[_i];
  3812. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  3813. return;
  3814. }
  3815. lengthComputable = lengthComputable && request._lengthComputable;
  3816. loaded += request._loaded;
  3817. total += request._total;
  3818. }
  3819. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  3820. };
  3821. GLTFLoader._GetProperty = function (context, array, index) {
  3822. if (!array || index == undefined || !array[index]) {
  3823. throw new Error(context + ": Failed to find index " + index);
  3824. }
  3825. return array[index];
  3826. };
  3827. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  3828. // Set defaults if undefined
  3829. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  3830. switch (mode) {
  3831. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  3832. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  3833. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  3834. default:
  3835. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  3836. return BABYLON.Texture.WRAP_ADDRESSMODE;
  3837. }
  3838. };
  3839. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  3840. // Set defaults if undefined
  3841. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  3842. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  3843. if (magFilter === 9729 /* LINEAR */) {
  3844. switch (minFilter) {
  3845. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  3846. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  3847. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  3848. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  3849. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  3850. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  3851. default:
  3852. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  3853. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  3854. }
  3855. }
  3856. else {
  3857. if (magFilter !== 9728 /* NEAREST */) {
  3858. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  3859. }
  3860. switch (minFilter) {
  3861. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  3862. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  3863. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  3864. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  3865. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  3866. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  3867. default:
  3868. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  3869. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  3870. }
  3871. }
  3872. };
  3873. GLTFLoader._GetNumComponents = function (context, type) {
  3874. switch (type) {
  3875. case "SCALAR": return 1;
  3876. case "VEC2": return 2;
  3877. case "VEC3": return 3;
  3878. case "VEC4": return 4;
  3879. case "MAT2": return 4;
  3880. case "MAT3": return 9;
  3881. case "MAT4": return 16;
  3882. }
  3883. throw new Error(context + ": Invalid type " + type);
  3884. };
  3885. GLTFLoader._ValidateUri = function (uri) {
  3886. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  3887. };
  3888. GLTFLoader.prototype._compileMaterialsAsync = function () {
  3889. var promises = new Array();
  3890. if (this._gltf.materials) {
  3891. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  3892. var material = _a[_i];
  3893. var babylonMaterial = material._babylonMaterial;
  3894. var babylonMeshes = material._babylonMeshes;
  3895. if (babylonMaterial && babylonMeshes) {
  3896. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  3897. var babylonMesh = babylonMeshes_1[_b];
  3898. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  3899. if (this.useClipPlane) {
  3900. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  3901. }
  3902. }
  3903. }
  3904. }
  3905. }
  3906. return Promise.all(promises).then(function () { });
  3907. };
  3908. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  3909. var promises = new Array();
  3910. var lights = this._babylonScene.lights;
  3911. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  3912. var light = lights_1[_i];
  3913. var generator = light.getShadowGenerator();
  3914. if (generator) {
  3915. promises.push(generator.forceCompilationAsync());
  3916. }
  3917. }
  3918. return Promise.all(promises).then(function () { });
  3919. };
  3920. GLTFLoader.prototype._abortRequests = function () {
  3921. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  3922. var request = _a[_i];
  3923. request.abort();
  3924. }
  3925. this._requests.length = 0;
  3926. };
  3927. GLTFLoader.prototype._releaseResources = function () {
  3928. if (this._gltf.images) {
  3929. for (var _i = 0, _a = this._gltf.images; _i < _a.length; _i++) {
  3930. var image = _a[_i];
  3931. if (image._objectURL) {
  3932. image._objectURL.then(function (value) {
  3933. URL.revokeObjectURL(value);
  3934. });
  3935. image._objectURL = undefined;
  3936. }
  3937. }
  3938. }
  3939. };
  3940. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  3941. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  3942. var name_2 = _a[_i];
  3943. var extension = this._extensions[name_2];
  3944. if (extension.enabled) {
  3945. var promise = actionAsync(extension);
  3946. if (promise) {
  3947. return promise;
  3948. }
  3949. }
  3950. }
  3951. return null;
  3952. };
  3953. GLTFLoader._Names = new Array();
  3954. GLTFLoader._Factories = {};
  3955. return GLTFLoader;
  3956. }());
  3957. GLTF2.GLTFLoader = GLTFLoader;
  3958. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  3959. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3960. })(BABYLON || (BABYLON = {}));
  3961. //# sourceMappingURL=babylon.glTFLoader.js.map
  3962. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  3963. var BABYLON;
  3964. (function (BABYLON) {
  3965. var GLTF2;
  3966. (function (GLTF2) {
  3967. var GLTFLoaderExtension = /** @class */ (function () {
  3968. function GLTFLoaderExtension(loader) {
  3969. this.enabled = true;
  3970. this._loader = loader;
  3971. }
  3972. // #region Overridable Methods
  3973. /** Override this method to modify the default behavior for loading scenes. */
  3974. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  3975. /** Override this method to modify the default behavior for loading nodes. */
  3976. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  3977. /** Override this method to modify the default behavior for loading materials. */
  3978. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  3979. /** Override this method to modify the default behavior for loading uris. */
  3980. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  3981. // #endregion
  3982. /** Helper method called by a loader extension to load an glTF extension. */
  3983. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  3984. var _this = this;
  3985. if (!property.extensions) {
  3986. return null;
  3987. }
  3988. var extensions = property.extensions;
  3989. var extension = extensions[this.name];
  3990. if (!extension) {
  3991. return null;
  3992. }
  3993. // Clear out the extension before executing the action to avoid recursing into the same property.
  3994. delete extensions[this.name];
  3995. return actionAsync(context + "/extensions/" + this.name, extension).then(function () {
  3996. // Restore the extension after completing the action.
  3997. extensions[_this.name] = extension;
  3998. });
  3999. };
  4000. /** Helper method called by the loader to allow extensions to override loading scenes. */
  4001. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  4002. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  4003. };
  4004. /** Helper method called by the loader to allow extensions to override loading nodes. */
  4005. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  4006. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  4007. };
  4008. /** Helper method called by the loader to allow extensions to override loading materials. */
  4009. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  4010. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  4011. };
  4012. /** Helper method called by the loader to allow extensions to override loading uris. */
  4013. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  4014. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  4015. };
  4016. return GLTFLoaderExtension;
  4017. }());
  4018. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  4019. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4020. })(BABYLON || (BABYLON = {}));
  4021. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  4022. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4023. var __extends = (this && this.__extends) || (function () {
  4024. var extendStatics = Object.setPrototypeOf ||
  4025. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4026. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4027. return function (d, b) {
  4028. extendStatics(d, b);
  4029. function __() { this.constructor = d; }
  4030. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4031. };
  4032. })();
  4033. var BABYLON;
  4034. (function (BABYLON) {
  4035. var GLTF2;
  4036. (function (GLTF2) {
  4037. var Extensions;
  4038. (function (Extensions) {
  4039. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  4040. var NAME = "MSFT_lod";
  4041. var MSFT_lod = /** @class */ (function (_super) {
  4042. __extends(MSFT_lod, _super);
  4043. function MSFT_lod() {
  4044. var _this = _super !== null && _super.apply(this, arguments) || this;
  4045. _this.name = NAME;
  4046. /**
  4047. * Maximum number of LODs to load, starting from the lowest LOD.
  4048. */
  4049. _this.maxLODsToLoad = Number.MAX_VALUE;
  4050. _this._loadingNodeLOD = null;
  4051. _this._loadNodeSignals = {};
  4052. _this._loadingMaterialLOD = null;
  4053. _this._loadMaterialSignals = {};
  4054. return _this;
  4055. }
  4056. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  4057. var _this = this;
  4058. return this._loadExtensionAsync(context, node, function (context, extension) {
  4059. var firstPromise;
  4060. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  4061. var _loop_1 = function (indexLOD) {
  4062. var nodeLOD = nodeLODs[indexLOD];
  4063. if (indexLOD !== 0) {
  4064. _this._loadingNodeLOD = nodeLOD;
  4065. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  4066. }
  4067. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  4068. if (indexLOD !== 0) {
  4069. var previousNodeLOD = nodeLODs[indexLOD - 1];
  4070. previousNodeLOD._babylonMesh.setEnabled(false);
  4071. }
  4072. if (indexLOD !== nodeLODs.length - 1) {
  4073. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  4074. _this._loadNodeSignals[nodeIndex].resolve();
  4075. delete _this._loadNodeSignals[nodeIndex];
  4076. }
  4077. });
  4078. if (indexLOD === 0) {
  4079. firstPromise = promise;
  4080. }
  4081. else {
  4082. _this._loader._completePromises.push(promise);
  4083. _this._loadingNodeLOD = null;
  4084. }
  4085. };
  4086. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  4087. _loop_1(indexLOD);
  4088. }
  4089. return firstPromise;
  4090. });
  4091. };
  4092. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  4093. var _this = this;
  4094. // Don't load material LODs if already loading a node LOD.
  4095. if (this._loadingNodeLOD) {
  4096. return null;
  4097. }
  4098. return this._loadExtensionAsync(context, material, function (context, extension) {
  4099. var firstPromise;
  4100. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  4101. var _loop_2 = function (indexLOD) {
  4102. var materialLOD = materialLODs[indexLOD];
  4103. if (indexLOD !== 0) {
  4104. _this._loadingMaterialLOD = materialLOD;
  4105. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  4106. }
  4107. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  4108. if (indexLOD !== materialLODs.length - 1) {
  4109. var materialIndex = materialLODs[indexLOD + 1]._index;
  4110. _this._loadMaterialSignals[materialIndex].resolve();
  4111. delete _this._loadMaterialSignals[materialIndex];
  4112. }
  4113. });
  4114. if (indexLOD === 0) {
  4115. firstPromise = promise;
  4116. }
  4117. else {
  4118. _this._loader._completePromises.push(promise);
  4119. _this._loadingMaterialLOD = null;
  4120. }
  4121. };
  4122. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  4123. _loop_2(indexLOD);
  4124. }
  4125. return firstPromise;
  4126. });
  4127. };
  4128. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  4129. var _this = this;
  4130. // Defer the loading of uris if loading a material or node LOD.
  4131. if (this._loadingMaterialLOD) {
  4132. var index = this._loadingMaterialLOD._index;
  4133. return this._loadMaterialSignals[index].promise.then(function () {
  4134. return _this._loader._loadUriAsync(context, uri);
  4135. });
  4136. }
  4137. else if (this._loadingNodeLOD) {
  4138. var index = this._loadingNodeLOD._index;
  4139. return this._loadNodeSignals[index].promise.then(function () {
  4140. return _this._loader._loadUriAsync(context, uri);
  4141. });
  4142. }
  4143. return null;
  4144. };
  4145. /**
  4146. * Gets an array of LOD properties from lowest to highest.
  4147. */
  4148. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  4149. if (this.maxLODsToLoad <= 0) {
  4150. throw new Error("maxLODsToLoad must be greater than zero");
  4151. }
  4152. var properties = new Array();
  4153. for (var i = ids.length - 1; i >= 0; i--) {
  4154. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  4155. if (properties.length === this.maxLODsToLoad) {
  4156. return properties;
  4157. }
  4158. }
  4159. properties.push(property);
  4160. return properties;
  4161. };
  4162. return MSFT_lod;
  4163. }(GLTF2.GLTFLoaderExtension));
  4164. Extensions.MSFT_lod = MSFT_lod;
  4165. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  4166. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4167. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4168. })(BABYLON || (BABYLON = {}));
  4169. //# sourceMappingURL=MSFT_lod.js.map
  4170. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4171. var __extends = (this && this.__extends) || (function () {
  4172. var extendStatics = Object.setPrototypeOf ||
  4173. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4174. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4175. return function (d, b) {
  4176. extendStatics(d, b);
  4177. function __() { this.constructor = d; }
  4178. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4179. };
  4180. })();
  4181. var BABYLON;
  4182. (function (BABYLON) {
  4183. var GLTF2;
  4184. (function (GLTF2) {
  4185. var Extensions;
  4186. (function (Extensions) {
  4187. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  4188. var NAME = "KHR_materials_pbrSpecularGlossiness";
  4189. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  4190. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  4191. function KHR_materials_pbrSpecularGlossiness() {
  4192. var _this = _super !== null && _super.apply(this, arguments) || this;
  4193. _this.name = NAME;
  4194. return _this;
  4195. }
  4196. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  4197. var _this = this;
  4198. return this._loadExtensionAsync(context, material, function (context, extension) {
  4199. material._babylonMeshes = material._babylonMeshes || [];
  4200. material._babylonMeshes.push(babylonMesh);
  4201. if (material._loaded) {
  4202. babylonMesh.material = material._babylonMaterial;
  4203. return material._loaded;
  4204. }
  4205. var promises = new Array();
  4206. var babylonMaterial = _this._loader._createMaterial(material);
  4207. material._babylonMaterial = babylonMaterial;
  4208. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  4209. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  4210. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  4211. babylonMesh.material = babylonMaterial;
  4212. return (material._loaded = Promise.all(promises).then(function () { }));
  4213. });
  4214. };
  4215. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  4216. var promises = new Array();
  4217. var babylonMaterial = material._babylonMaterial;
  4218. if (properties.diffuseFactor) {
  4219. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  4220. babylonMaterial.alpha = properties.diffuseFactor[3];
  4221. }
  4222. else {
  4223. babylonMaterial.albedoColor = BABYLON.Color3.White();
  4224. }
  4225. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  4226. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  4227. if (properties.diffuseTexture) {
  4228. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  4229. babylonMaterial.albedoTexture = texture;
  4230. }));
  4231. }
  4232. if (properties.specularGlossinessTexture) {
  4233. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  4234. babylonMaterial.reflectivityTexture = texture;
  4235. }));
  4236. babylonMaterial.reflectivityTexture.hasAlpha = true;
  4237. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  4238. }
  4239. loader._loadMaterialAlphaProperties(context, material);
  4240. return Promise.all(promises).then(function () { });
  4241. };
  4242. return KHR_materials_pbrSpecularGlossiness;
  4243. }(GLTF2.GLTFLoaderExtension));
  4244. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  4245. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  4246. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4247. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4248. })(BABYLON || (BABYLON = {}));
  4249. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  4250. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4251. var __extends = (this && this.__extends) || (function () {
  4252. var extendStatics = Object.setPrototypeOf ||
  4253. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4254. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4255. return function (d, b) {
  4256. extendStatics(d, b);
  4257. function __() { this.constructor = d; }
  4258. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4259. };
  4260. })();
  4261. var BABYLON;
  4262. (function (BABYLON) {
  4263. var GLTF2;
  4264. (function (GLTF2) {
  4265. var Extensions;
  4266. (function (Extensions) {
  4267. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  4268. var NAME = "KHR_lights";
  4269. var LightType;
  4270. (function (LightType) {
  4271. LightType["AMBIENT"] = "ambient";
  4272. LightType["DIRECTIONAL"] = "directional";
  4273. LightType["POINT"] = "point";
  4274. LightType["SPOT"] = "spot";
  4275. })(LightType || (LightType = {}));
  4276. var KHR_lights = /** @class */ (function (_super) {
  4277. __extends(KHR_lights, _super);
  4278. function KHR_lights() {
  4279. var _this = _super !== null && _super.apply(this, arguments) || this;
  4280. _this.name = NAME;
  4281. return _this;
  4282. }
  4283. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  4284. var _this = this;
  4285. return this._loadExtensionAsync(context, scene, function (context, extension) {
  4286. var promise = _this._loader._loadSceneAsync(context, scene);
  4287. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  4288. if (light.type !== LightType.AMBIENT) {
  4289. throw new Error(context + ": Only ambient lights are allowed on a scene");
  4290. }
  4291. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  4292. return promise;
  4293. });
  4294. };
  4295. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  4296. var _this = this;
  4297. return this._loadExtensionAsync(context, node, function (context, extension) {
  4298. var promise = _this._loader._loadNodeAsync(context, node);
  4299. var babylonLight;
  4300. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  4301. var name = node._babylonMesh.name;
  4302. switch (light.type) {
  4303. case LightType.AMBIENT: {
  4304. throw new Error(context + ": Ambient lights are not allowed on a node");
  4305. }
  4306. case LightType.DIRECTIONAL: {
  4307. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  4308. break;
  4309. }
  4310. case LightType.POINT: {
  4311. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  4312. break;
  4313. }
  4314. case LightType.SPOT: {
  4315. var spotLight = light;
  4316. // TODO: support inner and outer cone angles
  4317. //const innerConeAngle = spotLight.innerConeAngle || 0;
  4318. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  4319. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  4320. break;
  4321. }
  4322. default: {
  4323. throw new Error(context + ": Invalid light type " + light.type);
  4324. }
  4325. }
  4326. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  4327. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  4328. babylonLight.parent = node._babylonMesh;
  4329. return promise;
  4330. });
  4331. };
  4332. Object.defineProperty(KHR_lights.prototype, "_lights", {
  4333. get: function () {
  4334. var extensions = this._loader._gltf.extensions;
  4335. if (!extensions || !extensions[this.name]) {
  4336. throw new Error("#/extensions: " + this.name + " not found");
  4337. }
  4338. var extension = extensions[this.name];
  4339. return extension.lights;
  4340. },
  4341. enumerable: true,
  4342. configurable: true
  4343. });
  4344. return KHR_lights;
  4345. }(GLTF2.GLTFLoaderExtension));
  4346. Extensions.KHR_lights = KHR_lights;
  4347. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  4348. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4349. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4350. })(BABYLON || (BABYLON = {}));
  4351. //# sourceMappingURL=KHR_lights.js.map