babylonjs.loaders.js 359 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var BABYLON = root.BABYLON || this.BABYLON;
  4. if(typeof exports === 'object' && typeof module === 'object') {
  5. BABYLON = BABYLON || require("babylonjs");
  6. module.exports = factory(BABYLON);
  7. } else if(typeof define === 'function' && define.amd) {
  8. amdDependencies.push("babylonjs");
  9. define("babylonjs-loaders", amdDependencies, factory);
  10. } else if(typeof exports === 'object') {
  11. BABYLON = BABYLON || require("babylonjs");
  12. exports["babylonjs-loaders"] = factory(BABYLON);
  13. } else {
  14. root["BABYLON"] = factory(BABYLON);
  15. }
  16. })(this, function(BABYLON) {
  17. BABYLON = BABYLON || this.BABYLON;
  18. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  19. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  20. var BABYLON;
  21. (function (BABYLON) {
  22. var STLFileLoader = /** @class */ (function () {
  23. function STLFileLoader() {
  24. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  25. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  26. this.normalPattern = /normal[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
  27. this.vertexPattern = /vertex[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
  28. this.name = "stl";
  29. // force data to come in as an ArrayBuffer
  30. // we'll convert to string if it looks like it's an ASCII .stl
  31. this.extensions = {
  32. ".stl": { isBinary: true },
  33. };
  34. }
  35. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  36. var matches;
  37. if (typeof data !== "string") {
  38. if (this.isBinary(data)) {
  39. // binary .stl
  40. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  41. this.parseBinary(babylonMesh, data);
  42. if (meshes) {
  43. meshes.push(babylonMesh);
  44. }
  45. return true;
  46. }
  47. // ASCII .stl
  48. // convert to string
  49. var array_buffer = new Uint8Array(data);
  50. var str = '';
  51. for (var i = 0; i < data.byteLength; i++) {
  52. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  53. }
  54. data = str;
  55. }
  56. //if arrived here, data is a string, containing the STLA data.
  57. while (matches = this.solidPattern.exec(data)) {
  58. var meshName = matches[1];
  59. var meshNameFromEnd = matches[3];
  60. if (meshName != meshNameFromEnd) {
  61. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  62. return false;
  63. }
  64. // check meshesNames
  65. if (meshesNames && meshName) {
  66. if (meshesNames instanceof Array) {
  67. if (!meshesNames.indexOf(meshName)) {
  68. continue;
  69. }
  70. }
  71. else {
  72. if (meshName !== meshesNames) {
  73. continue;
  74. }
  75. }
  76. }
  77. // stl mesh name can be empty as well
  78. meshName = meshName || "stlmesh";
  79. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  80. this.parseASCII(babylonMesh, matches[2]);
  81. if (meshes) {
  82. meshes.push(babylonMesh);
  83. }
  84. }
  85. return true;
  86. };
  87. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  88. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  89. if (result) {
  90. scene.createDefaultCameraOrLight();
  91. }
  92. return result;
  93. };
  94. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  95. var container = new BABYLON.AssetContainer(scene);
  96. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  97. container.removeAllFromScene();
  98. return container;
  99. };
  100. STLFileLoader.prototype.isBinary = function (data) {
  101. // check if file size is correct for binary stl
  102. var faceSize, nFaces, reader;
  103. reader = new DataView(data);
  104. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  105. nFaces = reader.getUint32(80, true);
  106. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  107. return true;
  108. }
  109. // check characters higher than ASCII to confirm binary
  110. var fileLength = reader.byteLength;
  111. for (var index = 0; index < fileLength; index++) {
  112. if (reader.getUint8(index) > 127) {
  113. return true;
  114. }
  115. }
  116. return false;
  117. };
  118. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  119. var reader = new DataView(data);
  120. var faces = reader.getUint32(80, true);
  121. var dataOffset = 84;
  122. var faceLength = 12 * 4 + 2;
  123. var offset = 0;
  124. var positions = new Float32Array(faces * 3 * 3);
  125. var normals = new Float32Array(faces * 3 * 3);
  126. var indices = new Uint32Array(faces * 3);
  127. var indicesCount = 0;
  128. for (var face = 0; face < faces; face++) {
  129. var start = dataOffset + face * faceLength;
  130. var normalX = reader.getFloat32(start, true);
  131. var normalY = reader.getFloat32(start + 4, true);
  132. var normalZ = reader.getFloat32(start + 8, true);
  133. for (var i = 1; i <= 3; i++) {
  134. var vertexstart = start + i * 12;
  135. // ordering is intentional to match ascii import
  136. positions[offset] = reader.getFloat32(vertexstart, true);
  137. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  138. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  139. normals[offset] = normalX;
  140. normals[offset + 2] = normalY;
  141. normals[offset + 1] = normalZ;
  142. offset += 3;
  143. }
  144. indices[indicesCount] = indicesCount++;
  145. indices[indicesCount] = indicesCount++;
  146. indices[indicesCount] = indicesCount++;
  147. }
  148. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  149. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  150. mesh.setIndices(indices);
  151. mesh.computeWorldMatrix(true);
  152. };
  153. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  154. var positions = [];
  155. var normals = [];
  156. var indices = [];
  157. var indicesCount = 0;
  158. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  159. var matches;
  160. while (matches = this.facetsPattern.exec(solidData)) {
  161. var facet = matches[1];
  162. //one normal per face
  163. var normalMatches = this.normalPattern.exec(facet);
  164. this.normalPattern.lastIndex = 0;
  165. if (!normalMatches) {
  166. continue;
  167. }
  168. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  169. var vertexMatch;
  170. while (vertexMatch = this.vertexPattern.exec(facet)) {
  171. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  172. normals.push(normal[0], normal[1], normal[2]);
  173. }
  174. indices.push(indicesCount++, indicesCount++, indicesCount++);
  175. this.vertexPattern.lastIndex = 0;
  176. }
  177. this.facetsPattern.lastIndex = 0;
  178. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  179. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  180. mesh.setIndices(indices);
  181. mesh.computeWorldMatrix(true);
  182. };
  183. return STLFileLoader;
  184. }());
  185. BABYLON.STLFileLoader = STLFileLoader;
  186. if (BABYLON.SceneLoader) {
  187. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  188. }
  189. })(BABYLON || (BABYLON = {}));
  190. //# sourceMappingURL=babylon.stlFileLoader.js.map
  191. var BABYLON;
  192. (function (BABYLON) {
  193. /**
  194. * Class reading and parsing the MTL file bundled with the obj file.
  195. */
  196. var MTLFileLoader = /** @class */ (function () {
  197. function MTLFileLoader() {
  198. // All material loaded from the mtl will be set here
  199. this.materials = [];
  200. }
  201. /**
  202. * This function will read the mtl file and create each material described inside
  203. * This function could be improve by adding :
  204. * -some component missing (Ni, Tf...)
  205. * -including the specific options available
  206. *
  207. * @param scene
  208. * @param data
  209. * @param rootUrl
  210. */
  211. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  212. if (data instanceof ArrayBuffer) {
  213. return;
  214. }
  215. //Split the lines from the file
  216. var lines = data.split('\n');
  217. //Space char
  218. var delimiter_pattern = /\s+/;
  219. //Array with RGB colors
  220. var color;
  221. //New material
  222. var material = null;
  223. //Look at each line
  224. for (var i = 0; i < lines.length; i++) {
  225. var line = lines[i].trim();
  226. // Blank line or comment
  227. if (line.length === 0 || line.charAt(0) === '#') {
  228. continue;
  229. }
  230. //Get the first parameter (keyword)
  231. var pos = line.indexOf(' ');
  232. var key = (pos >= 0) ? line.substring(0, pos) : line;
  233. key = key.toLowerCase();
  234. //Get the data following the key
  235. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  236. //This mtl keyword will create the new material
  237. if (key === "newmtl") {
  238. //Check if it is the first material.
  239. // Materials specifications are described after this keyword.
  240. if (material) {
  241. //Add the previous material in the material array.
  242. this.materials.push(material);
  243. }
  244. //Create a new material.
  245. // value is the name of the material read in the mtl file
  246. material = new BABYLON.StandardMaterial(value, scene);
  247. }
  248. else if (key === "kd" && material) {
  249. // Diffuse color (color under white light) using RGB values
  250. //value = "r g b"
  251. color = value.split(delimiter_pattern, 3).map(parseFloat);
  252. //color = [r,g,b]
  253. //Set tghe color into the material
  254. material.diffuseColor = BABYLON.Color3.FromArray(color);
  255. }
  256. else if (key === "ka" && material) {
  257. // Ambient color (color under shadow) using RGB values
  258. //value = "r g b"
  259. color = value.split(delimiter_pattern, 3).map(parseFloat);
  260. //color = [r,g,b]
  261. //Set tghe color into the material
  262. material.ambientColor = BABYLON.Color3.FromArray(color);
  263. }
  264. else if (key === "ks" && material) {
  265. // Specular color (color when light is reflected from shiny surface) using RGB values
  266. //value = "r g b"
  267. color = value.split(delimiter_pattern, 3).map(parseFloat);
  268. //color = [r,g,b]
  269. //Set the color into the material
  270. material.specularColor = BABYLON.Color3.FromArray(color);
  271. }
  272. else if (key === "ke" && material) {
  273. // Emissive color using RGB values
  274. color = value.split(delimiter_pattern, 3).map(parseFloat);
  275. material.emissiveColor = BABYLON.Color3.FromArray(color);
  276. }
  277. else if (key === "ns" && material) {
  278. //value = "Integer"
  279. material.specularPower = parseFloat(value);
  280. }
  281. else if (key === "d" && material) {
  282. //d is dissolve for current material. It mean alpha for BABYLON
  283. material.alpha = parseFloat(value);
  284. //Texture
  285. //This part can be improved by adding the possible options of texture
  286. }
  287. else if (key === "map_ka" && material) {
  288. // ambient texture map with a loaded image
  289. //We must first get the folder of the image
  290. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  291. }
  292. else if (key === "map_kd" && material) {
  293. // Diffuse texture map with a loaded image
  294. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  295. }
  296. else if (key === "map_ks" && material) {
  297. // Specular texture map with a loaded image
  298. //We must first get the folder of the image
  299. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  300. }
  301. else if (key === "map_ns") {
  302. //Specular
  303. //Specular highlight component
  304. //We must first get the folder of the image
  305. //
  306. //Not supported by BABYLON
  307. //
  308. // continue;
  309. }
  310. else if (key === "map_bump" && material) {
  311. //The bump texture
  312. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  313. }
  314. else if (key === "map_d" && material) {
  315. // The dissolve of the material
  316. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  317. //Options for illumination
  318. }
  319. else if (key === "illum") {
  320. //Illumination
  321. if (value === "0") {
  322. //That mean Kd == Kd
  323. }
  324. else if (value === "1") {
  325. //Color on and Ambient on
  326. }
  327. else if (value === "2") {
  328. //Highlight on
  329. }
  330. else if (value === "3") {
  331. //Reflection on and Ray trace on
  332. }
  333. else if (value === "4") {
  334. //Transparency: Glass on, Reflection: Ray trace on
  335. }
  336. else if (value === "5") {
  337. //Reflection: Fresnel on and Ray trace on
  338. }
  339. else if (value === "6") {
  340. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  341. }
  342. else if (value === "7") {
  343. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  344. }
  345. else if (value === "8") {
  346. //Reflection on and Ray trace off
  347. }
  348. else if (value === "9") {
  349. //Transparency: Glass on, Reflection: Ray trace off
  350. }
  351. else if (value === "10") {
  352. //Casts shadows onto invisible surfaces
  353. }
  354. }
  355. else {
  356. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  357. }
  358. }
  359. //At the end of the file, add the last material
  360. if (material) {
  361. this.materials.push(material);
  362. }
  363. };
  364. /**
  365. * Gets the texture for the material.
  366. *
  367. * If the material is imported from input file,
  368. * We sanitize the url to ensure it takes the textre from aside the material.
  369. *
  370. * @param rootUrl The root url to load from
  371. * @param value The value stored in the mtl
  372. * @return The Texture
  373. */
  374. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  375. if (!value) {
  376. return null;
  377. }
  378. var url = rootUrl;
  379. // Load from input file.
  380. if (rootUrl === "file:") {
  381. var lastDelimiter = value.lastIndexOf("\\");
  382. if (lastDelimiter === -1) {
  383. lastDelimiter = value.lastIndexOf("/");
  384. }
  385. if (lastDelimiter > -1) {
  386. url += value.substr(lastDelimiter + 1);
  387. }
  388. else {
  389. url += value;
  390. }
  391. }
  392. // Not from input file.
  393. else {
  394. url += value;
  395. }
  396. return new BABYLON.Texture(url, scene);
  397. };
  398. return MTLFileLoader;
  399. }());
  400. BABYLON.MTLFileLoader = MTLFileLoader;
  401. var OBJFileLoader = /** @class */ (function () {
  402. function OBJFileLoader() {
  403. this.name = "obj";
  404. this.extensions = ".obj";
  405. this.obj = /^o/;
  406. this.group = /^g/;
  407. this.mtllib = /^mtllib /;
  408. this.usemtl = /^usemtl /;
  409. this.smooth = /^s /;
  410. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  411. // vn float float float
  412. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  413. // vt float float
  414. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  415. // f vertex vertex vertex ...
  416. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  417. // f vertex/uvs vertex/uvs vertex/uvs ...
  418. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  419. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  420. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  421. // f vertex//normal vertex//normal vertex//normal ...
  422. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  423. // f -vertex/-uvs/-normal -vertex/-uvs/-normal -vertex/-uvs/-normal ...
  424. this.facePattern5 = /f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/;
  425. }
  426. /**
  427. * Calls synchronously the MTL file attached to this obj.
  428. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  429. * Without this function materials are not displayed in the first frame (but displayed after).
  430. * In consequence it is impossible to get material information in your HTML file
  431. *
  432. * @param url The URL of the MTL file
  433. * @param rootUrl
  434. * @param onSuccess Callback function to be called when the MTL file is loaded
  435. * @private
  436. */
  437. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  438. //The complete path to the mtl file
  439. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  440. // Loads through the babylon tools to allow fileInput search.
  441. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  442. };
  443. /**
  444. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  445. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  446. * @param scene the scene the meshes should be added to
  447. * @param data the glTF data to load
  448. * @param rootUrl root url to load from
  449. * @param onProgress event that fires when loading progress has occured
  450. * @param fileName Defines the name of the file to load
  451. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  452. */
  453. OBJFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  454. //get the meshes from OBJ file
  455. return this._parseSolid(meshesNames, scene, data, rootUrl).then(function (meshes) {
  456. return {
  457. meshes: meshes,
  458. particleSystems: [],
  459. skeletons: [],
  460. animationGroups: []
  461. };
  462. });
  463. };
  464. /**
  465. * Imports all objects from the loaded glTF data and adds them to the scene
  466. * @param scene the scene the objects should be added to
  467. * @param data the glTF data to load
  468. * @param rootUrl root url to load from
  469. * @param onProgress event that fires when loading progress has occured
  470. * @param fileName Defines the name of the file to load
  471. * @returns a promise which completes when objects have been loaded to the scene
  472. */
  473. OBJFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  474. //Get the 3D model
  475. return this.importMeshAsync(null, scene, data, rootUrl, onProgress).then(function () {
  476. // return void
  477. });
  478. };
  479. /**
  480. * Load into an asset container.
  481. * @param scene The scene to load into
  482. * @param data The data to import
  483. * @param rootUrl The root url for scene and resources
  484. * @param onProgress The callback when the load progresses
  485. * @param fileName Defines the name of the file to load
  486. * @returns The loaded asset container
  487. */
  488. OBJFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress, fileName) {
  489. return this.importMeshAsync(null, scene, data, rootUrl).then(function (result) {
  490. var container = new BABYLON.AssetContainer(scene);
  491. result.meshes.forEach(function (mesh) { return container.meshes.push(mesh); });
  492. container.removeAllFromScene();
  493. return container;
  494. });
  495. };
  496. /**
  497. * Read the OBJ file and create an Array of meshes.
  498. * Each mesh contains all information given by the OBJ and the MTL file.
  499. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  500. *
  501. * @param meshesNames
  502. * @param scene BABYLON.Scene The scene where are displayed the data
  503. * @param data String The content of the obj file
  504. * @param rootUrl String The path to the folder
  505. * @returns Array<AbstractMesh>
  506. * @private
  507. */
  508. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  509. var _this = this;
  510. var positions = []; //values for the positions of vertices
  511. var normals = []; //Values for the normals
  512. var uvs = []; //Values for the textures
  513. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  514. var handledMesh; //The current mesh of meshes array
  515. var indicesForBabylon = []; //The list of indices for VertexData
  516. var wrappedPositionForBabylon = []; //The list of position in vectors
  517. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  518. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  519. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  520. var curPositionInIndices = 0;
  521. var hasMeshes = false; //Meshes are defined in the file
  522. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  523. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  524. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  525. var triangles = []; //Indices from new triangles coming from polygons
  526. var materialNameFromObj = ""; //The name of the current material
  527. var fileToLoad = ""; //The name of the mtlFile to load
  528. var materialsFromMTLFile = new MTLFileLoader();
  529. var objMeshName = ""; //The name of the current obj mesh
  530. var increment = 1; //Id for meshes created by the multimaterial
  531. var isFirstMaterial = true;
  532. /**
  533. * Search for obj in the given array.
  534. * This function is called to check if a couple of data already exists in an array.
  535. *
  536. * If found, returns the index of the founded tuple index. Returns -1 if not found
  537. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  538. * @param obj Array<number>
  539. * @returns {boolean}
  540. */
  541. var isInArray = function (arr, obj) {
  542. if (!arr[obj[0]])
  543. arr[obj[0]] = { normals: [], idx: [] };
  544. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  545. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  546. };
  547. var isInArrayUV = function (arr, obj) {
  548. if (!arr[obj[0]])
  549. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  550. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  551. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  552. return arr[obj[0]].idx[idx];
  553. }
  554. return -1;
  555. };
  556. /**
  557. * This function set the data for each triangle.
  558. * Data are position, normals and uvs
  559. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  560. * If the tuple already exist, add only their indice
  561. *
  562. * @param indicePositionFromObj Integer The index in positions array
  563. * @param indiceUvsFromObj Integer The index in uvs array
  564. * @param indiceNormalFromObj Integer The index in normals array
  565. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  566. * @param textureVectorFromOBJ Vector3 The value of uvs
  567. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  568. */
  569. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  570. //Check if this tuple already exists in the list of tuples
  571. var _index;
  572. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  573. _index = isInArrayUV(tuplePosNorm, [
  574. indicePositionFromObj,
  575. indiceNormalFromObj,
  576. indiceUvsFromObj
  577. ]);
  578. }
  579. else {
  580. _index = isInArray(tuplePosNorm, [
  581. indicePositionFromObj,
  582. indiceNormalFromObj
  583. ]);
  584. }
  585. //If it not exists
  586. if (_index == -1) {
  587. //Add an new indice.
  588. //The array of indices is only an array with his length equal to the number of triangles - 1.
  589. //We add vertices data in this order
  590. indicesForBabylon.push(wrappedPositionForBabylon.length);
  591. //Push the position of vertice for Babylon
  592. //Each element is a BABYLON.Vector3(x,y,z)
  593. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  594. //Push the uvs for Babylon
  595. //Each element is a BABYLON.Vector3(u,v)
  596. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  597. //Push the normals for Babylon
  598. //Each element is a BABYLON.Vector3(x,y,z)
  599. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  600. //Add the tuple in the comparison list
  601. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  602. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  603. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  604. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  605. }
  606. else {
  607. //The tuple already exists
  608. //Add the index of the already existing tuple
  609. //At this index we can get the value of position, normal and uvs of vertex
  610. indicesForBabylon.push(_index);
  611. }
  612. };
  613. /**
  614. * Transform BABYLON.Vector() object onto 3 digits in an array
  615. */
  616. var unwrapData = function () {
  617. //Every array has the same length
  618. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  619. //Push the x, y, z values of each element in the unwrapped array
  620. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  621. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  622. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  623. }
  624. // Reset arrays for the next new meshes
  625. wrappedPositionForBabylon = [];
  626. wrappedNormalsForBabylon = [];
  627. wrappedUvsForBabylon = [];
  628. tuplePosNorm = [];
  629. curPositionInIndices = 0;
  630. };
  631. /**
  632. * Create triangles from polygons by recursion
  633. * The best to understand how it works is to draw it in the same time you get the recursion.
  634. * It is important to notice that a triangle is a polygon
  635. * We get 5 patterns of face defined in OBJ File :
  636. * facePattern1 = ["1","2","3","4","5","6"]
  637. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  638. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  639. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  640. * facePattern5 = ["-1/-1/-1","-2/-2/-2","-3/-3/-3","-4/-4/-4","-5/-5/-5","-6/-6/-6"]
  641. * Each pattern is divided by the same method
  642. * @param face Array[String] The indices of elements
  643. * @param v Integer The variable to increment
  644. */
  645. var getTriangles = function (face, v) {
  646. //Work for each element of the array
  647. if (v + 1 < face.length) {
  648. //Add on the triangle variable the indexes to obtain triangles
  649. triangles.push(face[0], face[v], face[v + 1]);
  650. //Incrementation for recursion
  651. v += 1;
  652. //Recursion
  653. getTriangles(face, v);
  654. }
  655. //Result obtained after 2 iterations:
  656. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  657. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  658. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  659. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  660. //Pattern5 => triangle = ["-1/-1/-1","-2/-2/-2","-3/-3/-3","-1/-1/-1","-3/-3/-3","-4/-4/-4"];
  661. };
  662. /**
  663. * Create triangles and push the data for each polygon for the pattern 1
  664. * In this pattern we get vertice positions
  665. * @param face
  666. * @param v
  667. */
  668. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  669. //Get the indices of triangles for each polygon
  670. getTriangles(face, v);
  671. //For each element in the triangles array.
  672. //This var could contains 1 to an infinity of triangles
  673. for (var k = 0; k < triangles.length; k++) {
  674. // Set position indice
  675. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  676. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  677. positions[indicePositionFromObj], //Get the vectors data
  678. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  679. );
  680. }
  681. //Reset variable for the next line
  682. triangles = [];
  683. };
  684. /**
  685. * Create triangles and push the data for each polygon for the pattern 2
  686. * In this pattern we get vertice positions and uvsu
  687. * @param face
  688. * @param v
  689. */
  690. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  691. //Get the indices of triangles for each polygon
  692. getTriangles(face, v);
  693. for (var k = 0; k < triangles.length; k++) {
  694. //triangle[k] = "1/1"
  695. //Split the data for getting position and uv
  696. var point = triangles[k].split("/"); // ["1", "1"]
  697. //Set position indice
  698. var indicePositionFromObj = parseInt(point[0]) - 1;
  699. //Set uv indice
  700. var indiceUvsFromObj = parseInt(point[1]) - 1;
  701. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  702. positions[indicePositionFromObj], //Get the values for each element
  703. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  704. );
  705. }
  706. //Reset variable for the next line
  707. triangles = [];
  708. };
  709. /**
  710. * Create triangles and push the data for each polygon for the pattern 3
  711. * In this pattern we get vertice positions, uvs and normals
  712. * @param face
  713. * @param v
  714. */
  715. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  716. //Get the indices of triangles for each polygon
  717. getTriangles(face, v);
  718. for (var k = 0; k < triangles.length; k++) {
  719. //triangle[k] = "1/1/1"
  720. //Split the data for getting position, uv, and normals
  721. var point = triangles[k].split("/"); // ["1", "1", "1"]
  722. // Set position indice
  723. var indicePositionFromObj = parseInt(point[0]) - 1;
  724. // Set uv indice
  725. var indiceUvsFromObj = parseInt(point[1]) - 1;
  726. // Set normal indice
  727. var indiceNormalFromObj = parseInt(point[2]) - 1;
  728. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  729. );
  730. }
  731. //Reset variable for the next line
  732. triangles = [];
  733. };
  734. /**
  735. * Create triangles and push the data for each polygon for the pattern 4
  736. * In this pattern we get vertice positions and normals
  737. * @param face
  738. * @param v
  739. */
  740. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  741. getTriangles(face, v);
  742. for (var k = 0; k < triangles.length; k++) {
  743. //triangle[k] = "1//1"
  744. //Split the data for getting position and normals
  745. var point = triangles[k].split("//"); // ["1", "1"]
  746. // We check indices, and normals
  747. var indicePositionFromObj = parseInt(point[0]) - 1;
  748. var indiceNormalFromObj = parseInt(point[1]) - 1;
  749. setData(indicePositionFromObj, 1, //Default value for uv
  750. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  751. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  752. }
  753. //Reset variable for the next line
  754. triangles = [];
  755. };
  756. /**
  757. * Create triangles and push the data for each polygon for the pattern 3
  758. * In this pattern we get vertice positions, uvs and normals
  759. * @param face
  760. * @param v
  761. */
  762. var setDataForCurrentFaceWithPattern5 = function (face, v) {
  763. //Get the indices of triangles for each polygon
  764. getTriangles(face, v);
  765. for (var k = 0; k < triangles.length; k++) {
  766. //triangle[k] = "-1/-1/-1"
  767. //Split the data for getting position, uv, and normals
  768. var point = triangles[k].split("/"); // ["-1", "-1", "-1"]
  769. // Set position indice
  770. var indicePositionFromObj = positions.length + parseInt(point[0]);
  771. // Set uv indice
  772. var indiceUvsFromObj = uvs.length + parseInt(point[1]);
  773. // Set normal indice
  774. var indiceNormalFromObj = normals.length + parseInt(point[2]);
  775. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  776. );
  777. }
  778. //Reset variable for the next line
  779. triangles = [];
  780. };
  781. var addPreviousObjMesh = function () {
  782. //Check if it is not the first mesh. Otherwise we don't have data.
  783. if (meshesFromObj.length > 0) {
  784. //Get the previous mesh for applying the data about the faces
  785. //=> in obj file, faces definition append after the name of the mesh
  786. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  787. //Set the data into Array for the mesh
  788. unwrapData();
  789. // Reverse tab. Otherwise face are displayed in the wrong sens
  790. indicesForBabylon.reverse();
  791. //Set the information for the mesh
  792. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  793. handledMesh.indices = indicesForBabylon.slice();
  794. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  795. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  796. handledMesh.uvs = unwrappedUVForBabylon.slice();
  797. //Reset the array for the next mesh
  798. indicesForBabylon = [];
  799. unwrappedPositionsForBabylon = [];
  800. unwrappedNormalsForBabylon = [];
  801. unwrappedUVForBabylon = [];
  802. }
  803. };
  804. //Main function
  805. //Split the file into lines
  806. var lines = data.split('\n');
  807. //Look at each line
  808. for (var i = 0; i < lines.length; i++) {
  809. var line = lines[i].trim();
  810. var result;
  811. //Comment or newLine
  812. if (line.length === 0 || line.charAt(0) === '#') {
  813. continue;
  814. //Get information about one position possible for the vertices
  815. }
  816. else if ((result = this.vertexPattern.exec(line)) !== null) {
  817. //Create a Vector3 with the position x, y, z
  818. //Value of result:
  819. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  820. //Add the Vector in the list of positions
  821. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  822. }
  823. else if ((result = this.normalPattern.exec(line)) !== null) {
  824. //Create a Vector3 with the normals x, y, z
  825. //Value of result
  826. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  827. //Add the Vector in the list of normals
  828. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  829. }
  830. else if ((result = this.uvPattern.exec(line)) !== null) {
  831. //Create a Vector2 with the normals u, v
  832. //Value of result
  833. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  834. //Add the Vector in the list of uvs
  835. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  836. //Identify patterns of faces
  837. //Face could be defined in different type of pattern
  838. }
  839. else if ((result = this.facePattern3.exec(line)) !== null) {
  840. //Value of result:
  841. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  842. //Set the data for this face
  843. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  844. 1);
  845. }
  846. else if ((result = this.facePattern4.exec(line)) !== null) {
  847. //Value of result:
  848. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  849. //Set the data for this face
  850. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  851. 1);
  852. }
  853. else if ((result = this.facePattern5.exec(line)) !== null) {
  854. //Value of result:
  855. //["f -1/-1/-1 -2/-2/-2 -3/-3/-3", "-1/-1/-1 -2/-2/-2 -3/-3/-3"...]
  856. //Set the data for this face
  857. setDataForCurrentFaceWithPattern5(result[1].trim().split(" "), // ["-1/-1/-1", "-2/-2/-2", "-3/-3/-3"]
  858. 1);
  859. }
  860. else if ((result = this.facePattern2.exec(line)) !== null) {
  861. //Value of result:
  862. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  863. //Set the data for this face
  864. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  865. 1);
  866. }
  867. else if ((result = this.facePattern1.exec(line)) !== null) {
  868. //Value of result
  869. //["f 1 2 3", "1 2 3"...]
  870. //Set the data for this face
  871. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  872. 1);
  873. //Define a mesh or an object
  874. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  875. }
  876. else if (this.group.test(line) || this.obj.test(line)) {
  877. //Create a new mesh corresponding to the name of the group.
  878. //Definition of the mesh
  879. var objMesh =
  880. //Set the name of the current obj mesh
  881. {
  882. name: line.substring(2).trim(),
  883. indices: undefined,
  884. positions: undefined,
  885. normals: undefined,
  886. uvs: undefined,
  887. materialName: ""
  888. };
  889. addPreviousObjMesh();
  890. //Push the last mesh created with only the name
  891. meshesFromObj.push(objMesh);
  892. //Set this variable to indicate that now meshesFromObj has objects defined inside
  893. hasMeshes = true;
  894. isFirstMaterial = true;
  895. increment = 1;
  896. //Keyword for applying a material
  897. }
  898. else if (this.usemtl.test(line)) {
  899. //Get the name of the material
  900. materialNameFromObj = line.substring(7).trim();
  901. //If this new material is in the same mesh
  902. if (!isFirstMaterial) {
  903. //Set the data for the previous mesh
  904. addPreviousObjMesh();
  905. //Create a new mesh
  906. var objMesh =
  907. //Set the name of the current obj mesh
  908. {
  909. name: objMeshName + "_mm" + increment.toString(),
  910. indices: undefined,
  911. positions: undefined,
  912. normals: undefined,
  913. uvs: undefined,
  914. materialName: materialNameFromObj
  915. };
  916. increment++;
  917. //If meshes are already defined
  918. meshesFromObj.push(objMesh);
  919. }
  920. //Set the material name if the previous line define a mesh
  921. if (hasMeshes && isFirstMaterial) {
  922. //Set the material name to the previous mesh (1 material per mesh)
  923. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  924. isFirstMaterial = false;
  925. }
  926. //Keyword for loading the mtl file
  927. }
  928. else if (this.mtllib.test(line)) {
  929. //Get the name of mtl file
  930. fileToLoad = line.substring(7).trim();
  931. //Apply smoothing
  932. }
  933. else if (this.smooth.test(line)) {
  934. // smooth shading => apply smoothing
  935. //Toda y I don't know it work with babylon and with obj.
  936. //With the obj file an integer is set
  937. }
  938. else {
  939. //If there is another possibility
  940. console.log("Unhandled expression at line : " + line);
  941. }
  942. }
  943. //At the end of the file, add the last mesh into the meshesFromObj array
  944. if (hasMeshes) {
  945. //Set the data for the last mesh
  946. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  947. //Reverse indices for displaying faces in the good sens
  948. indicesForBabylon.reverse();
  949. //Get the good array
  950. unwrapData();
  951. //Set array
  952. handledMesh.indices = indicesForBabylon;
  953. handledMesh.positions = unwrappedPositionsForBabylon;
  954. handledMesh.normals = unwrappedNormalsForBabylon;
  955. handledMesh.uvs = unwrappedUVForBabylon;
  956. }
  957. //If any o or g keyword found, create a mesj with a random id
  958. if (!hasMeshes) {
  959. // reverse tab of indices
  960. indicesForBabylon.reverse();
  961. //Get positions normals uvs
  962. unwrapData();
  963. //Set data for one mesh
  964. meshesFromObj.push({
  965. name: BABYLON.Geometry.RandomId(),
  966. indices: indicesForBabylon,
  967. positions: unwrappedPositionsForBabylon,
  968. normals: unwrappedNormalsForBabylon,
  969. uvs: unwrappedUVForBabylon,
  970. materialName: materialNameFromObj
  971. });
  972. }
  973. //Create a BABYLON.Mesh list
  974. var babylonMeshesArray = []; //The mesh for babylon
  975. var materialToUse = new Array();
  976. //Set data for each mesh
  977. for (var j = 0; j < meshesFromObj.length; j++) {
  978. //check meshesNames (stlFileLoader)
  979. if (meshesNames && meshesFromObj[j].name) {
  980. if (meshesNames instanceof Array) {
  981. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  982. continue;
  983. }
  984. }
  985. else {
  986. if (meshesFromObj[j].name !== meshesNames) {
  987. continue;
  988. }
  989. }
  990. }
  991. //Get the current mesh
  992. //Set the data with VertexBuffer for each mesh
  993. handledMesh = meshesFromObj[j];
  994. //Create a BABYLON.Mesh with the name of the obj mesh
  995. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  996. //Push the name of the material to an array
  997. //This is indispensable for the importMesh function
  998. materialToUse.push(meshesFromObj[j].materialName);
  999. var vertexData = new BABYLON.VertexData(); //The container for the values
  1000. //Set the data for the babylonMesh
  1001. vertexData.positions = handledMesh.positions;
  1002. vertexData.normals = handledMesh.normals;
  1003. vertexData.uvs = handledMesh.uvs;
  1004. vertexData.indices = handledMesh.indices;
  1005. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  1006. vertexData.applyToMesh(babylonMesh);
  1007. if (OBJFileLoader.INVERT_Y) {
  1008. babylonMesh.scaling.y *= -1;
  1009. }
  1010. //Push the mesh into an array
  1011. babylonMeshesArray.push(babylonMesh);
  1012. }
  1013. var mtlPromises = [];
  1014. //load the materials
  1015. //Check if we have a file to load
  1016. if (fileToLoad !== "") {
  1017. //Load the file synchronously
  1018. mtlPromises.push(new Promise(function (resolve, reject) {
  1019. _this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  1020. try {
  1021. //Create materials thanks MTLLoader function
  1022. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  1023. //Look at each material loaded in the mtl file
  1024. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  1025. //Three variables to get all meshes with the same material
  1026. var startIndex = 0;
  1027. var _indices = [];
  1028. var _index;
  1029. //The material from MTL file is used in the meshes loaded
  1030. //Push the indice in an array
  1031. //Check if the material is not used for another mesh
  1032. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  1033. _indices.push(_index);
  1034. startIndex = _index + 1;
  1035. }
  1036. //If the material is not used dispose it
  1037. if (_index == -1 && _indices.length == 0) {
  1038. //If the material is not needed, remove it
  1039. materialsFromMTLFile.materials[n].dispose();
  1040. }
  1041. else {
  1042. for (var o = 0; o < _indices.length; o++) {
  1043. //Apply the material to the BABYLON.Mesh for each mesh with the material
  1044. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  1045. }
  1046. }
  1047. }
  1048. resolve();
  1049. }
  1050. catch (e) {
  1051. reject(e);
  1052. }
  1053. });
  1054. }));
  1055. }
  1056. //Return an array with all BABYLON.Mesh
  1057. return Promise.all(mtlPromises).then(function () {
  1058. return babylonMeshesArray;
  1059. });
  1060. };
  1061. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  1062. OBJFileLoader.INVERT_Y = false;
  1063. return OBJFileLoader;
  1064. }());
  1065. BABYLON.OBJFileLoader = OBJFileLoader;
  1066. if (BABYLON.SceneLoader) {
  1067. //Add this loader into the register plugin
  1068. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  1069. }
  1070. })(BABYLON || (BABYLON = {}));
  1071. //# sourceMappingURL=babylon.objFileLoader.js.map
  1072. var BABYLON;
  1073. (function (BABYLON) {
  1074. /**
  1075. * Mode that determines the coordinate system to use.
  1076. */
  1077. var GLTFLoaderCoordinateSystemMode;
  1078. (function (GLTFLoaderCoordinateSystemMode) {
  1079. /**
  1080. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  1081. */
  1082. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  1083. /**
  1084. * Sets the useRightHandedSystem flag on the scene.
  1085. */
  1086. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  1087. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  1088. /**
  1089. * Mode that determines what animations will start.
  1090. */
  1091. var GLTFLoaderAnimationStartMode;
  1092. (function (GLTFLoaderAnimationStartMode) {
  1093. /**
  1094. * No animation will start.
  1095. */
  1096. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  1097. /**
  1098. * The first animation will start.
  1099. */
  1100. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  1101. /**
  1102. * All animations will start.
  1103. */
  1104. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  1105. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  1106. /**
  1107. * Loader state.
  1108. */
  1109. var GLTFLoaderState;
  1110. (function (GLTFLoaderState) {
  1111. /**
  1112. * The asset is loading.
  1113. */
  1114. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  1115. /**
  1116. * The asset is ready for rendering.
  1117. */
  1118. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  1119. /**
  1120. * The asset is completely loaded.
  1121. */
  1122. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  1123. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  1124. /**
  1125. * File loader for loading glTF files into a scene.
  1126. */
  1127. var GLTFFileLoader = /** @class */ (function () {
  1128. function GLTFFileLoader() {
  1129. // --------------
  1130. // Common options
  1131. // --------------
  1132. /**
  1133. * Raised when the asset has been parsed
  1134. */
  1135. this.onParsedObservable = new BABYLON.Observable();
  1136. // ----------
  1137. // V2 options
  1138. // ----------
  1139. /**
  1140. * The coordinate system mode. Defaults to AUTO.
  1141. */
  1142. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  1143. /**
  1144. * The animation start mode. Defaults to FIRST.
  1145. */
  1146. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  1147. /**
  1148. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  1149. */
  1150. this.compileMaterials = false;
  1151. /**
  1152. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  1153. */
  1154. this.useClipPlane = false;
  1155. /**
  1156. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  1157. */
  1158. this.compileShadowGenerators = false;
  1159. /**
  1160. * Defines if the Alpha blended materials are only applied as coverage.
  1161. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  1162. * If true, no extra effects are applied to transparent pixels.
  1163. */
  1164. this.transparencyAsCoverage = false;
  1165. /**
  1166. * Function called before loading a url referenced by the asset.
  1167. */
  1168. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  1169. /**
  1170. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  1171. */
  1172. this.onMeshLoadedObservable = new BABYLON.Observable();
  1173. /**
  1174. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  1175. */
  1176. this.onTextureLoadedObservable = new BABYLON.Observable();
  1177. /**
  1178. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  1179. */
  1180. this.onMaterialLoadedObservable = new BABYLON.Observable();
  1181. /**
  1182. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  1183. */
  1184. this.onCameraLoadedObservable = new BABYLON.Observable();
  1185. /**
  1186. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  1187. * For assets with LODs, raised when all of the LODs are complete.
  1188. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  1189. */
  1190. this.onCompleteObservable = new BABYLON.Observable();
  1191. /**
  1192. * Observable raised when an error occurs.
  1193. */
  1194. this.onErrorObservable = new BABYLON.Observable();
  1195. /**
  1196. * Observable raised after the loader is disposed.
  1197. */
  1198. this.onDisposeObservable = new BABYLON.Observable();
  1199. /**
  1200. * Observable raised after a loader extension is created.
  1201. * Set additional options for a loader extension in this event.
  1202. */
  1203. this.onExtensionLoadedObservable = new BABYLON.Observable();
  1204. /**
  1205. * Defines if the loader should validate the asset.
  1206. */
  1207. this.validate = false;
  1208. /**
  1209. * Observable raised after validation when validate is set to true. The event data is the result of the validation.
  1210. */
  1211. this.onValidatedObservable = new BABYLON.Observable();
  1212. this._loader = null;
  1213. /**
  1214. * Name of the loader ("gltf")
  1215. */
  1216. this.name = "gltf";
  1217. /**
  1218. * Supported file extensions of the loader (.gltf, .glb)
  1219. */
  1220. this.extensions = {
  1221. ".gltf": { isBinary: false },
  1222. ".glb": { isBinary: true }
  1223. };
  1224. this._logIndentLevel = 0;
  1225. this._loggingEnabled = false;
  1226. /** @hidden */
  1227. this._log = this._logDisabled;
  1228. this._capturePerformanceCounters = false;
  1229. /** @hidden */
  1230. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  1231. /** @hidden */
  1232. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  1233. }
  1234. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  1235. /**
  1236. * Raised when the asset has been parsed
  1237. */
  1238. set: function (callback) {
  1239. if (this._onParsedObserver) {
  1240. this.onParsedObservable.remove(this._onParsedObserver);
  1241. }
  1242. this._onParsedObserver = this.onParsedObservable.add(callback);
  1243. },
  1244. enumerable: true,
  1245. configurable: true
  1246. });
  1247. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  1248. /**
  1249. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  1250. */
  1251. set: function (callback) {
  1252. if (this._onMeshLoadedObserver) {
  1253. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  1254. }
  1255. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  1256. },
  1257. enumerable: true,
  1258. configurable: true
  1259. });
  1260. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  1261. /**
  1262. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  1263. */
  1264. set: function (callback) {
  1265. if (this._onTextureLoadedObserver) {
  1266. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  1267. }
  1268. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  1269. },
  1270. enumerable: true,
  1271. configurable: true
  1272. });
  1273. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  1274. /**
  1275. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  1276. */
  1277. set: function (callback) {
  1278. if (this._onMaterialLoadedObserver) {
  1279. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  1280. }
  1281. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  1282. },
  1283. enumerable: true,
  1284. configurable: true
  1285. });
  1286. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  1287. /**
  1288. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  1289. */
  1290. set: function (callback) {
  1291. if (this._onCameraLoadedObserver) {
  1292. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  1293. }
  1294. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  1295. },
  1296. enumerable: true,
  1297. configurable: true
  1298. });
  1299. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  1300. /**
  1301. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  1302. * For assets with LODs, raised when all of the LODs are complete.
  1303. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  1304. */
  1305. set: function (callback) {
  1306. if (this._onCompleteObserver) {
  1307. this.onCompleteObservable.remove(this._onCompleteObserver);
  1308. }
  1309. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  1310. },
  1311. enumerable: true,
  1312. configurable: true
  1313. });
  1314. Object.defineProperty(GLTFFileLoader.prototype, "onError", {
  1315. /**
  1316. * Callback raised when an error occurs.
  1317. */
  1318. set: function (callback) {
  1319. if (this._onErrorObserver) {
  1320. this.onErrorObservable.remove(this._onErrorObserver);
  1321. }
  1322. this._onErrorObserver = this.onErrorObservable.add(callback);
  1323. },
  1324. enumerable: true,
  1325. configurable: true
  1326. });
  1327. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  1328. /**
  1329. * Callback raised after the loader is disposed.
  1330. */
  1331. set: function (callback) {
  1332. if (this._onDisposeObserver) {
  1333. this.onDisposeObservable.remove(this._onDisposeObserver);
  1334. }
  1335. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  1336. },
  1337. enumerable: true,
  1338. configurable: true
  1339. });
  1340. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  1341. /**
  1342. * Callback raised after a loader extension is created.
  1343. */
  1344. set: function (callback) {
  1345. if (this._onExtensionLoadedObserver) {
  1346. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  1347. }
  1348. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  1349. },
  1350. enumerable: true,
  1351. configurable: true
  1352. });
  1353. Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", {
  1354. /**
  1355. * Defines if the loader logging is enabled.
  1356. */
  1357. get: function () {
  1358. return this._loggingEnabled;
  1359. },
  1360. set: function (value) {
  1361. if (this._loggingEnabled === value) {
  1362. return;
  1363. }
  1364. this._loggingEnabled = value;
  1365. if (this._loggingEnabled) {
  1366. this._log = this._logEnabled;
  1367. }
  1368. else {
  1369. this._log = this._logDisabled;
  1370. }
  1371. },
  1372. enumerable: true,
  1373. configurable: true
  1374. });
  1375. Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", {
  1376. /**
  1377. * Defines if the loader should capture performance counters.
  1378. */
  1379. get: function () {
  1380. return this._capturePerformanceCounters;
  1381. },
  1382. set: function (value) {
  1383. if (this._capturePerformanceCounters === value) {
  1384. return;
  1385. }
  1386. this._capturePerformanceCounters = value;
  1387. if (this._capturePerformanceCounters) {
  1388. this._startPerformanceCounter = this._startPerformanceCounterEnabled;
  1389. this._endPerformanceCounter = this._endPerformanceCounterEnabled;
  1390. }
  1391. else {
  1392. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  1393. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  1394. }
  1395. },
  1396. enumerable: true,
  1397. configurable: true
  1398. });
  1399. Object.defineProperty(GLTFFileLoader.prototype, "onValidated", {
  1400. /**
  1401. * Callback raised after a loader extension is created.
  1402. */
  1403. set: function (callback) {
  1404. if (this._onValidatedObserver) {
  1405. this.onValidatedObservable.remove(this._onValidatedObserver);
  1406. }
  1407. this._onValidatedObserver = this.onValidatedObservable.add(callback);
  1408. },
  1409. enumerable: true,
  1410. configurable: true
  1411. });
  1412. /**
  1413. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  1414. */
  1415. GLTFFileLoader.prototype.dispose = function () {
  1416. if (this._loader) {
  1417. this._loader.dispose();
  1418. this._loader = null;
  1419. }
  1420. this._clear();
  1421. this.onDisposeObservable.notifyObservers(undefined);
  1422. this.onDisposeObservable.clear();
  1423. };
  1424. /** @hidden */
  1425. GLTFFileLoader.prototype._clear = function () {
  1426. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  1427. this.onMeshLoadedObservable.clear();
  1428. this.onTextureLoadedObservable.clear();
  1429. this.onMaterialLoadedObservable.clear();
  1430. this.onCameraLoadedObservable.clear();
  1431. this.onCompleteObservable.clear();
  1432. this.onExtensionLoadedObservable.clear();
  1433. };
  1434. /**
  1435. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  1436. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  1437. * @param scene the scene the meshes should be added to
  1438. * @param data the glTF data to load
  1439. * @param rootUrl root url to load from
  1440. * @param onProgress event that fires when loading progress has occured
  1441. * @param fileName Defines the name of the file to load
  1442. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  1443. */
  1444. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  1445. var _this = this;
  1446. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  1447. _this._log("Loading " + (fileName || ""));
  1448. _this._loader = _this._getLoader(loaderData);
  1449. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress, fileName);
  1450. });
  1451. };
  1452. /**
  1453. * Imports all objects from the loaded glTF data and adds them to the scene
  1454. * @param scene the scene the objects should be added to
  1455. * @param data the glTF data to load
  1456. * @param rootUrl root url to load from
  1457. * @param onProgress event that fires when loading progress has occured
  1458. * @param fileName Defines the name of the file to load
  1459. * @returns a promise which completes when objects have been loaded to the scene
  1460. */
  1461. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  1462. var _this = this;
  1463. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  1464. _this._log("Loading " + (fileName || ""));
  1465. _this._loader = _this._getLoader(loaderData);
  1466. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress, fileName);
  1467. });
  1468. };
  1469. /**
  1470. * Load into an asset container.
  1471. * @param scene The scene to load into
  1472. * @param data The data to import
  1473. * @param rootUrl The root url for scene and resources
  1474. * @param onProgress The callback when the load progresses
  1475. * @param fileName Defines the name of the file to load
  1476. * @returns The loaded asset container
  1477. */
  1478. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress, fileName) {
  1479. var _this = this;
  1480. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  1481. _this._log("Loading " + (fileName || ""));
  1482. _this._loader = _this._getLoader(loaderData);
  1483. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress, fileName).then(function (result) {
  1484. var container = new BABYLON.AssetContainer(scene);
  1485. Array.prototype.push.apply(container.meshes, result.meshes);
  1486. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  1487. Array.prototype.push.apply(container.skeletons, result.skeletons);
  1488. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  1489. container.removeAllFromScene();
  1490. return container;
  1491. });
  1492. });
  1493. };
  1494. /**
  1495. * If the data string can be loaded directly.
  1496. * @param data string contianing the file data
  1497. * @returns if the data can be loaded directly
  1498. */
  1499. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  1500. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  1501. };
  1502. /**
  1503. * Instantiates a glTF file loader plugin.
  1504. * @returns the created plugin
  1505. */
  1506. GLTFFileLoader.prototype.createPlugin = function () {
  1507. return new GLTFFileLoader();
  1508. };
  1509. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  1510. /**
  1511. * The loader state or null if the loader is not active.
  1512. */
  1513. get: function () {
  1514. return this._loader ? this._loader.state : null;
  1515. },
  1516. enumerable: true,
  1517. configurable: true
  1518. });
  1519. /**
  1520. * Returns a promise that resolves when the asset is completely loaded.
  1521. * @returns a promise that resolves when the asset is completely loaded.
  1522. */
  1523. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  1524. var _this = this;
  1525. return new Promise(function (resolve, reject) {
  1526. _this.onCompleteObservable.addOnce(function () {
  1527. resolve();
  1528. });
  1529. _this.onErrorObservable.addOnce(function (reason) {
  1530. reject(reason);
  1531. });
  1532. });
  1533. };
  1534. GLTFFileLoader.prototype._parseAsync = function (scene, data, rootUrl, fileName) {
  1535. var _this = this;
  1536. return Promise.resolve().then(function () {
  1537. var unpacked = (data instanceof ArrayBuffer) ? _this._unpackBinary(data) : { json: data, bin: null };
  1538. return _this._validateAsync(scene, unpacked.json, rootUrl, fileName).then(function () {
  1539. _this._startPerformanceCounter("Parse JSON");
  1540. _this._log("JSON length: " + unpacked.json.length);
  1541. var loaderData = {
  1542. json: JSON.parse(unpacked.json),
  1543. bin: unpacked.bin
  1544. };
  1545. _this._endPerformanceCounter("Parse JSON");
  1546. _this.onParsedObservable.notifyObservers(loaderData);
  1547. _this.onParsedObservable.clear();
  1548. return loaderData;
  1549. });
  1550. });
  1551. };
  1552. GLTFFileLoader.prototype._validateAsync = function (scene, json, rootUrl, fileName) {
  1553. var _this = this;
  1554. if (!this.validate || typeof GLTFValidator === "undefined") {
  1555. return Promise.resolve();
  1556. }
  1557. this._startPerformanceCounter("Validate JSON");
  1558. var options = {
  1559. externalResourceFunction: function (uri) {
  1560. return _this.preprocessUrlAsync(rootUrl + uri)
  1561. .then(function (url) { return scene._loadFileAsync(url, true, true); })
  1562. .then(function (data) { return new Uint8Array(data); });
  1563. }
  1564. };
  1565. if (fileName && fileName.substr(0, 5) !== "data:") {
  1566. options.uri = (rootUrl === "file:" ? fileName : "" + rootUrl + fileName);
  1567. }
  1568. return GLTFValidator.validateString(json, options).then(function (result) {
  1569. _this._endPerformanceCounter("Validate JSON");
  1570. _this.onValidatedObservable.notifyObservers(result);
  1571. _this.onValidatedObservable.clear();
  1572. });
  1573. };
  1574. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  1575. var asset = loaderData.json.asset || {};
  1576. this._log("Asset version: " + asset.version);
  1577. asset.minVersion && this._log("Asset minimum version: " + asset.minVersion);
  1578. asset.generator && this._log("Asset generator: " + asset.generator);
  1579. var version = GLTFFileLoader._parseVersion(asset.version);
  1580. if (!version) {
  1581. throw new Error("Invalid version: " + asset.version);
  1582. }
  1583. if (asset.minVersion !== undefined) {
  1584. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  1585. if (!minVersion) {
  1586. throw new Error("Invalid minimum version: " + asset.minVersion);
  1587. }
  1588. if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
  1589. throw new Error("Incompatible minimum version: " + asset.minVersion);
  1590. }
  1591. }
  1592. var createLoaders = {
  1593. 1: GLTFFileLoader._CreateGLTFLoaderV1,
  1594. 2: GLTFFileLoader._CreateGLTFLoaderV2
  1595. };
  1596. var createLoader = createLoaders[version.major];
  1597. if (!createLoader) {
  1598. throw new Error("Unsupported version: " + asset.version);
  1599. }
  1600. return createLoader(this);
  1601. };
  1602. GLTFFileLoader.prototype._unpackBinary = function (data) {
  1603. this._startPerformanceCounter("Unpack binary");
  1604. this._log("Binary length: " + data.byteLength);
  1605. var Binary = {
  1606. Magic: 0x46546C67
  1607. };
  1608. var binaryReader = new BinaryReader(data);
  1609. var magic = binaryReader.readUint32();
  1610. if (magic !== Binary.Magic) {
  1611. throw new Error("Unexpected magic: " + magic);
  1612. }
  1613. var version = binaryReader.readUint32();
  1614. if (this.loggingEnabled) {
  1615. this._log("Binary version: " + version);
  1616. }
  1617. var unpacked;
  1618. switch (version) {
  1619. case 1: {
  1620. unpacked = this._unpackBinaryV1(binaryReader);
  1621. break;
  1622. }
  1623. case 2: {
  1624. unpacked = this._unpackBinaryV2(binaryReader);
  1625. break;
  1626. }
  1627. default: {
  1628. throw new Error("Unsupported version: " + version);
  1629. }
  1630. }
  1631. this._endPerformanceCounter("Unpack binary");
  1632. return unpacked;
  1633. };
  1634. GLTFFileLoader.prototype._unpackBinaryV1 = function (binaryReader) {
  1635. var ContentFormat = {
  1636. JSON: 0
  1637. };
  1638. var length = binaryReader.readUint32();
  1639. if (length != binaryReader.getLength()) {
  1640. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  1641. }
  1642. var contentLength = binaryReader.readUint32();
  1643. var contentFormat = binaryReader.readUint32();
  1644. var content;
  1645. switch (contentFormat) {
  1646. case ContentFormat.JSON: {
  1647. content = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength));
  1648. break;
  1649. }
  1650. default: {
  1651. throw new Error("Unexpected content format: " + contentFormat);
  1652. }
  1653. }
  1654. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  1655. var body = binaryReader.readUint8Array(bytesRemaining);
  1656. return {
  1657. json: content,
  1658. bin: body
  1659. };
  1660. };
  1661. GLTFFileLoader.prototype._unpackBinaryV2 = function (binaryReader) {
  1662. var ChunkFormat = {
  1663. JSON: 0x4E4F534A,
  1664. BIN: 0x004E4942
  1665. };
  1666. var length = binaryReader.readUint32();
  1667. if (length !== binaryReader.getLength()) {
  1668. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  1669. }
  1670. // JSON chunk
  1671. var chunkLength = binaryReader.readUint32();
  1672. var chunkFormat = binaryReader.readUint32();
  1673. if (chunkFormat !== ChunkFormat.JSON) {
  1674. throw new Error("First chunk format is not JSON");
  1675. }
  1676. var json = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength));
  1677. // Look for BIN chunk
  1678. var bin = null;
  1679. while (binaryReader.getPosition() < binaryReader.getLength()) {
  1680. var chunkLength_1 = binaryReader.readUint32();
  1681. var chunkFormat_1 = binaryReader.readUint32();
  1682. switch (chunkFormat_1) {
  1683. case ChunkFormat.JSON: {
  1684. throw new Error("Unexpected JSON chunk");
  1685. }
  1686. case ChunkFormat.BIN: {
  1687. bin = binaryReader.readUint8Array(chunkLength_1);
  1688. break;
  1689. }
  1690. default: {
  1691. // ignore unrecognized chunkFormat
  1692. binaryReader.skipBytes(chunkLength_1);
  1693. break;
  1694. }
  1695. }
  1696. }
  1697. return {
  1698. json: json,
  1699. bin: bin
  1700. };
  1701. };
  1702. GLTFFileLoader._parseVersion = function (version) {
  1703. if (version === "1.0" || version === "1.0.1") {
  1704. return {
  1705. major: 1,
  1706. minor: 0
  1707. };
  1708. }
  1709. var match = (version + "").match(/^(\d+)\.(\d+)/);
  1710. if (!match) {
  1711. return null;
  1712. }
  1713. return {
  1714. major: parseInt(match[1]),
  1715. minor: parseInt(match[2])
  1716. };
  1717. };
  1718. GLTFFileLoader._compareVersion = function (a, b) {
  1719. if (a.major > b.major)
  1720. return 1;
  1721. if (a.major < b.major)
  1722. return -1;
  1723. if (a.minor > b.minor)
  1724. return 1;
  1725. if (a.minor < b.minor)
  1726. return -1;
  1727. return 0;
  1728. };
  1729. GLTFFileLoader._decodeBufferToText = function (buffer) {
  1730. var result = "";
  1731. var length = buffer.byteLength;
  1732. for (var i = 0; i < length; i++) {
  1733. result += String.fromCharCode(buffer[i]);
  1734. }
  1735. return result;
  1736. };
  1737. /** @hidden */
  1738. GLTFFileLoader.prototype._logOpen = function (message) {
  1739. this._log(message);
  1740. this._logIndentLevel++;
  1741. };
  1742. /** @hidden */
  1743. GLTFFileLoader.prototype._logClose = function () {
  1744. --this._logIndentLevel;
  1745. };
  1746. GLTFFileLoader.prototype._logEnabled = function (message) {
  1747. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  1748. BABYLON.Tools.Log("" + spaces + message);
  1749. };
  1750. GLTFFileLoader.prototype._logDisabled = function (message) {
  1751. };
  1752. GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
  1753. BABYLON.Tools.StartPerformanceCounter(counterName);
  1754. };
  1755. GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
  1756. };
  1757. GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
  1758. BABYLON.Tools.EndPerformanceCounter(counterName);
  1759. };
  1760. GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
  1761. };
  1762. // ----------
  1763. // V1 options
  1764. // ----------
  1765. /**
  1766. * Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders.
  1767. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  1768. * Defaults to true.
  1769. * @hidden
  1770. */
  1771. GLTFFileLoader.IncrementalLoading = true;
  1772. /**
  1773. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  1774. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  1775. * @hidden
  1776. */
  1777. GLTFFileLoader.HomogeneousCoordinates = false;
  1778. GLTFFileLoader._logSpaces = " ";
  1779. return GLTFFileLoader;
  1780. }());
  1781. BABYLON.GLTFFileLoader = GLTFFileLoader;
  1782. var BinaryReader = /** @class */ (function () {
  1783. function BinaryReader(arrayBuffer) {
  1784. this._arrayBuffer = arrayBuffer;
  1785. this._dataView = new DataView(arrayBuffer);
  1786. this._byteOffset = 0;
  1787. }
  1788. BinaryReader.prototype.getPosition = function () {
  1789. return this._byteOffset;
  1790. };
  1791. BinaryReader.prototype.getLength = function () {
  1792. return this._arrayBuffer.byteLength;
  1793. };
  1794. BinaryReader.prototype.readUint32 = function () {
  1795. var value = this._dataView.getUint32(this._byteOffset, true);
  1796. this._byteOffset += 4;
  1797. return value;
  1798. };
  1799. BinaryReader.prototype.readUint8Array = function (length) {
  1800. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  1801. this._byteOffset += length;
  1802. return value;
  1803. };
  1804. BinaryReader.prototype.skipBytes = function (length) {
  1805. this._byteOffset += length;
  1806. };
  1807. return BinaryReader;
  1808. }());
  1809. if (BABYLON.SceneLoader) {
  1810. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  1811. }
  1812. })(BABYLON || (BABYLON = {}));
  1813. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  1814. var BABYLON;
  1815. (function (BABYLON) {
  1816. var GLTF1;
  1817. (function (GLTF1) {
  1818. /**
  1819. * Enums
  1820. */
  1821. var EComponentType;
  1822. (function (EComponentType) {
  1823. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  1824. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  1825. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  1826. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  1827. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  1828. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  1829. var EShaderType;
  1830. (function (EShaderType) {
  1831. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  1832. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  1833. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  1834. var EParameterType;
  1835. (function (EParameterType) {
  1836. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  1837. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  1838. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  1839. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  1840. EParameterType[EParameterType["INT"] = 5124] = "INT";
  1841. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  1842. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  1843. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  1844. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  1845. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  1846. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  1847. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  1848. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  1849. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  1850. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  1851. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  1852. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  1853. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  1854. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  1855. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  1856. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  1857. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  1858. var ETextureWrapMode;
  1859. (function (ETextureWrapMode) {
  1860. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  1861. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  1862. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  1863. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  1864. var ETextureFilterType;
  1865. (function (ETextureFilterType) {
  1866. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  1867. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  1868. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  1869. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  1870. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  1871. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  1872. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  1873. var ETextureFormat;
  1874. (function (ETextureFormat) {
  1875. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  1876. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  1877. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  1878. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  1879. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  1880. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  1881. var ECullingType;
  1882. (function (ECullingType) {
  1883. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  1884. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  1885. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  1886. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  1887. var EBlendingFunction;
  1888. (function (EBlendingFunction) {
  1889. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  1890. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  1891. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  1892. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  1893. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  1894. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  1895. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  1896. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  1897. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  1898. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  1899. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  1900. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  1901. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  1902. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  1903. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  1904. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  1905. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  1906. })(BABYLON || (BABYLON = {}));
  1907. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  1908. var BABYLON;
  1909. (function (BABYLON) {
  1910. var GLTF1;
  1911. (function (GLTF1) {
  1912. /**
  1913. * Tokenizer. Used for shaders compatibility
  1914. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  1915. */
  1916. var ETokenType;
  1917. (function (ETokenType) {
  1918. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  1919. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  1920. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  1921. })(ETokenType || (ETokenType = {}));
  1922. var Tokenizer = /** @class */ (function () {
  1923. function Tokenizer(toParse) {
  1924. this._pos = 0;
  1925. this.currentToken = ETokenType.UNKNOWN;
  1926. this.currentIdentifier = "";
  1927. this.currentString = "";
  1928. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  1929. this._toParse = toParse;
  1930. this._maxPos = toParse.length;
  1931. }
  1932. Tokenizer.prototype.getNextToken = function () {
  1933. if (this.isEnd())
  1934. return ETokenType.END_OF_INPUT;
  1935. this.currentString = this.read();
  1936. this.currentToken = ETokenType.UNKNOWN;
  1937. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  1938. this.currentToken = ETokenType.IDENTIFIER;
  1939. this.currentIdentifier = this.currentString;
  1940. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  1941. this.currentIdentifier += this.currentString;
  1942. this.forward();
  1943. }
  1944. }
  1945. return this.currentToken;
  1946. };
  1947. Tokenizer.prototype.peek = function () {
  1948. return this._toParse[this._pos];
  1949. };
  1950. Tokenizer.prototype.read = function () {
  1951. return this._toParse[this._pos++];
  1952. };
  1953. Tokenizer.prototype.forward = function () {
  1954. this._pos++;
  1955. };
  1956. Tokenizer.prototype.isEnd = function () {
  1957. return this._pos >= this._maxPos;
  1958. };
  1959. return Tokenizer;
  1960. }());
  1961. /**
  1962. * Values
  1963. */
  1964. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  1965. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  1966. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  1967. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  1968. /**
  1969. * Parse
  1970. */
  1971. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  1972. for (var buf in parsedBuffers) {
  1973. var parsedBuffer = parsedBuffers[buf];
  1974. gltfRuntime.buffers[buf] = parsedBuffer;
  1975. gltfRuntime.buffersCount++;
  1976. }
  1977. };
  1978. var parseShaders = function (parsedShaders, gltfRuntime) {
  1979. for (var sha in parsedShaders) {
  1980. var parsedShader = parsedShaders[sha];
  1981. gltfRuntime.shaders[sha] = parsedShader;
  1982. gltfRuntime.shaderscount++;
  1983. }
  1984. };
  1985. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  1986. for (var object in parsedObjects) {
  1987. var parsedObject = parsedObjects[object];
  1988. gltfRuntime[runtimeProperty][object] = parsedObject;
  1989. }
  1990. };
  1991. /**
  1992. * Utils
  1993. */
  1994. var normalizeUVs = function (buffer) {
  1995. if (!buffer) {
  1996. return;
  1997. }
  1998. for (var i = 0; i < buffer.length / 2; i++) {
  1999. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  2000. }
  2001. };
  2002. var getAttribute = function (attributeParameter) {
  2003. if (attributeParameter.semantic === "NORMAL") {
  2004. return "normal";
  2005. }
  2006. else if (attributeParameter.semantic === "POSITION") {
  2007. return "position";
  2008. }
  2009. else if (attributeParameter.semantic === "JOINT") {
  2010. return "matricesIndices";
  2011. }
  2012. else if (attributeParameter.semantic === "WEIGHT") {
  2013. return "matricesWeights";
  2014. }
  2015. else if (attributeParameter.semantic === "COLOR") {
  2016. return "color";
  2017. }
  2018. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  2019. var channel = Number(attributeParameter.semantic.split("_")[1]);
  2020. return "uv" + (channel === 0 ? "" : channel + 1);
  2021. }
  2022. return null;
  2023. };
  2024. /**
  2025. * Loads and creates animations
  2026. */
  2027. var loadAnimations = function (gltfRuntime) {
  2028. for (var anim in gltfRuntime.animations) {
  2029. var animation = gltfRuntime.animations[anim];
  2030. if (!animation.channels || !animation.samplers) {
  2031. continue;
  2032. }
  2033. var lastAnimation = null;
  2034. for (var i = 0; i < animation.channels.length; i++) {
  2035. // Get parameters and load buffers
  2036. var channel = animation.channels[i];
  2037. var sampler = animation.samplers[channel.sampler];
  2038. if (!sampler) {
  2039. continue;
  2040. }
  2041. var inputData = null;
  2042. var outputData = null;
  2043. if (animation.parameters) {
  2044. inputData = animation.parameters[sampler.input];
  2045. outputData = animation.parameters[sampler.output];
  2046. }
  2047. else {
  2048. inputData = sampler.input;
  2049. outputData = sampler.output;
  2050. }
  2051. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  2052. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  2053. var targetID = channel.target.id;
  2054. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  2055. if (targetNode === null) {
  2056. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  2057. }
  2058. if (targetNode === null) {
  2059. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  2060. continue;
  2061. }
  2062. var isBone = targetNode instanceof BABYLON.Bone;
  2063. // Get target path (position, rotation or scaling)
  2064. var targetPath = channel.target.path;
  2065. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  2066. if (targetPathIndex !== -1) {
  2067. targetPath = babylonAnimationPaths[targetPathIndex];
  2068. }
  2069. // Determine animation type
  2070. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  2071. if (!isBone) {
  2072. if (targetPath === "rotationQuaternion") {
  2073. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  2074. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  2075. }
  2076. else {
  2077. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  2078. }
  2079. }
  2080. // Create animation and key frames
  2081. var babylonAnimation = null;
  2082. var keys = [];
  2083. var arrayOffset = 0;
  2084. var modifyKey = false;
  2085. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  2086. babylonAnimation = lastAnimation;
  2087. modifyKey = true;
  2088. }
  2089. if (!modifyKey) {
  2090. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  2091. }
  2092. // For each frame
  2093. for (var j = 0; j < bufferInput.length; j++) {
  2094. var value = null;
  2095. if (targetPath === "rotationQuaternion") { // VEC4
  2096. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  2097. arrayOffset += 4;
  2098. }
  2099. else { // Position and scaling are VEC3
  2100. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  2101. arrayOffset += 3;
  2102. }
  2103. if (isBone) {
  2104. var bone = targetNode;
  2105. var translation = BABYLON.Vector3.Zero();
  2106. var rotationQuaternion = new BABYLON.Quaternion();
  2107. var scaling = BABYLON.Vector3.Zero();
  2108. // Warning on decompose
  2109. var mat = bone.getBaseMatrix();
  2110. if (modifyKey && lastAnimation) {
  2111. mat = lastAnimation.getKeys()[j].value;
  2112. }
  2113. mat.decompose(scaling, rotationQuaternion, translation);
  2114. if (targetPath === "position") {
  2115. translation = value;
  2116. }
  2117. else if (targetPath === "rotationQuaternion") {
  2118. rotationQuaternion = value;
  2119. }
  2120. else {
  2121. scaling = value;
  2122. }
  2123. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  2124. }
  2125. if (!modifyKey) {
  2126. keys.push({
  2127. frame: bufferInput[j],
  2128. value: value
  2129. });
  2130. }
  2131. else if (lastAnimation) {
  2132. lastAnimation.getKeys()[j].value = value;
  2133. }
  2134. }
  2135. // Finish
  2136. if (!modifyKey && babylonAnimation) {
  2137. babylonAnimation.setKeys(keys);
  2138. targetNode.animations.push(babylonAnimation);
  2139. }
  2140. lastAnimation = babylonAnimation;
  2141. gltfRuntime.scene.stopAnimation(targetNode);
  2142. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  2143. }
  2144. }
  2145. };
  2146. /**
  2147. * Returns the bones transformation matrix
  2148. */
  2149. var configureBoneTransformation = function (node) {
  2150. var mat = null;
  2151. if (node.translation || node.rotation || node.scale) {
  2152. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  2153. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  2154. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  2155. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  2156. }
  2157. else {
  2158. mat = BABYLON.Matrix.FromArray(node.matrix);
  2159. }
  2160. return mat;
  2161. };
  2162. /**
  2163. * Returns the parent bone
  2164. */
  2165. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  2166. // Try to find
  2167. for (var i = 0; i < newSkeleton.bones.length; i++) {
  2168. if (newSkeleton.bones[i].name === jointName) {
  2169. return newSkeleton.bones[i];
  2170. }
  2171. }
  2172. // Not found, search in gltf nodes
  2173. var nodes = gltfRuntime.nodes;
  2174. for (var nde in nodes) {
  2175. var node = nodes[nde];
  2176. if (!node.jointName) {
  2177. continue;
  2178. }
  2179. var children = node.children;
  2180. for (var i = 0; i < children.length; i++) {
  2181. var child = gltfRuntime.nodes[children[i]];
  2182. if (!child.jointName) {
  2183. continue;
  2184. }
  2185. if (child.jointName === jointName) {
  2186. var mat = configureBoneTransformation(node);
  2187. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  2188. bone.id = nde;
  2189. return bone;
  2190. }
  2191. }
  2192. }
  2193. return null;
  2194. };
  2195. /**
  2196. * Returns the appropriate root node
  2197. */
  2198. var getNodeToRoot = function (nodesToRoot, id) {
  2199. for (var i = 0; i < nodesToRoot.length; i++) {
  2200. var nodeToRoot = nodesToRoot[i];
  2201. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  2202. var child = nodeToRoot.node.children[j];
  2203. if (child === id) {
  2204. return nodeToRoot.bone;
  2205. }
  2206. }
  2207. }
  2208. return null;
  2209. };
  2210. /**
  2211. * Returns the node with the joint name
  2212. */
  2213. var getJointNode = function (gltfRuntime, jointName) {
  2214. var nodes = gltfRuntime.nodes;
  2215. var node = nodes[jointName];
  2216. if (node) {
  2217. return {
  2218. node: node,
  2219. id: jointName
  2220. };
  2221. }
  2222. for (var nde in nodes) {
  2223. node = nodes[nde];
  2224. if (node.jointName === jointName) {
  2225. return {
  2226. node: node,
  2227. id: nde
  2228. };
  2229. }
  2230. }
  2231. return null;
  2232. };
  2233. /**
  2234. * Checks if a nodes is in joints
  2235. */
  2236. var nodeIsInJoints = function (skins, id) {
  2237. for (var i = 0; i < skins.jointNames.length; i++) {
  2238. if (skins.jointNames[i] === id) {
  2239. return true;
  2240. }
  2241. }
  2242. return false;
  2243. };
  2244. /**
  2245. * Fills the nodes to root for bones and builds hierarchy
  2246. */
  2247. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  2248. // Creates nodes for root
  2249. for (var nde in gltfRuntime.nodes) {
  2250. var node = gltfRuntime.nodes[nde];
  2251. var id = nde;
  2252. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  2253. continue;
  2254. }
  2255. // Create node to root bone
  2256. var mat = configureBoneTransformation(node);
  2257. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  2258. bone.id = id;
  2259. nodesToRoot.push({ bone: bone, node: node, id: id });
  2260. }
  2261. // Parenting
  2262. for (var i = 0; i < nodesToRoot.length; i++) {
  2263. var nodeToRoot = nodesToRoot[i];
  2264. var children = nodeToRoot.node.children;
  2265. for (var j = 0; j < children.length; j++) {
  2266. var child = null;
  2267. for (var k = 0; k < nodesToRoot.length; k++) {
  2268. if (nodesToRoot[k].id === children[j]) {
  2269. child = nodesToRoot[k];
  2270. break;
  2271. }
  2272. }
  2273. if (child) {
  2274. child.bone._parent = nodeToRoot.bone;
  2275. nodeToRoot.bone.children.push(child.bone);
  2276. }
  2277. }
  2278. }
  2279. };
  2280. /**
  2281. * Imports a skeleton
  2282. */
  2283. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  2284. if (!newSkeleton) {
  2285. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  2286. }
  2287. if (!skins.babylonSkeleton) {
  2288. return newSkeleton;
  2289. }
  2290. // Find the root bones
  2291. var nodesToRoot = [];
  2292. var nodesToRootToAdd = [];
  2293. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  2294. newSkeleton.bones = [];
  2295. // Joints
  2296. for (var i = 0; i < skins.jointNames.length; i++) {
  2297. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  2298. if (!jointNode) {
  2299. continue;
  2300. }
  2301. var node = jointNode.node;
  2302. if (!node) {
  2303. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  2304. continue;
  2305. }
  2306. var id = jointNode.id;
  2307. // Optimize, if the bone already exists...
  2308. var existingBone = gltfRuntime.scene.getBoneByID(id);
  2309. if (existingBone) {
  2310. newSkeleton.bones.push(existingBone);
  2311. continue;
  2312. }
  2313. // Search for parent bone
  2314. var foundBone = false;
  2315. var parentBone = null;
  2316. for (var j = 0; j < i; j++) {
  2317. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  2318. if (!jointNode_1) {
  2319. continue;
  2320. }
  2321. var joint = jointNode_1.node;
  2322. if (!joint) {
  2323. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  2324. continue;
  2325. }
  2326. var children = joint.children;
  2327. if (!children) {
  2328. continue;
  2329. }
  2330. foundBone = false;
  2331. for (var k = 0; k < children.length; k++) {
  2332. if (children[k] === id) {
  2333. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  2334. foundBone = true;
  2335. break;
  2336. }
  2337. }
  2338. if (foundBone) {
  2339. break;
  2340. }
  2341. }
  2342. // Create bone
  2343. var mat = configureBoneTransformation(node);
  2344. if (!parentBone && nodesToRoot.length > 0) {
  2345. parentBone = getNodeToRoot(nodesToRoot, id);
  2346. if (parentBone) {
  2347. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  2348. nodesToRootToAdd.push(parentBone);
  2349. }
  2350. }
  2351. }
  2352. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  2353. bone.id = id;
  2354. }
  2355. // Polish
  2356. var bones = newSkeleton.bones;
  2357. newSkeleton.bones = [];
  2358. for (var i = 0; i < skins.jointNames.length; i++) {
  2359. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  2360. if (!jointNode) {
  2361. continue;
  2362. }
  2363. for (var j = 0; j < bones.length; j++) {
  2364. if (bones[j].id === jointNode.id) {
  2365. newSkeleton.bones.push(bones[j]);
  2366. break;
  2367. }
  2368. }
  2369. }
  2370. newSkeleton.prepare();
  2371. // Finish
  2372. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  2373. newSkeleton.bones.push(nodesToRootToAdd[i]);
  2374. }
  2375. return newSkeleton;
  2376. };
  2377. /**
  2378. * Imports a mesh and its geometries
  2379. */
  2380. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  2381. if (!newMesh) {
  2382. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  2383. newMesh.id = id;
  2384. }
  2385. if (!node.babylonNode) {
  2386. return newMesh;
  2387. }
  2388. var subMaterials = [];
  2389. var vertexData = null;
  2390. var verticesStarts = new Array();
  2391. var verticesCounts = new Array();
  2392. var indexStarts = new Array();
  2393. var indexCounts = new Array();
  2394. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  2395. var meshID = meshes[meshIndex];
  2396. var mesh = gltfRuntime.meshes[meshID];
  2397. if (!mesh) {
  2398. continue;
  2399. }
  2400. // Positions, normals and UVs
  2401. for (var i = 0; i < mesh.primitives.length; i++) {
  2402. // Temporary vertex data
  2403. var tempVertexData = new BABYLON.VertexData();
  2404. var primitive = mesh.primitives[i];
  2405. if (primitive.mode !== 4) {
  2406. // continue;
  2407. }
  2408. var attributes = primitive.attributes;
  2409. var accessor = null;
  2410. var buffer = null;
  2411. // Set positions, normal and uvs
  2412. for (var semantic in attributes) {
  2413. // Link accessor and buffer view
  2414. accessor = gltfRuntime.accessors[attributes[semantic]];
  2415. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  2416. if (semantic === "NORMAL") {
  2417. tempVertexData.normals = new Float32Array(buffer.length);
  2418. tempVertexData.normals.set(buffer);
  2419. }
  2420. else if (semantic === "POSITION") {
  2421. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  2422. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  2423. for (var j = 0; j < buffer.length; j += 4) {
  2424. tempVertexData.positions[j] = buffer[j];
  2425. tempVertexData.positions[j + 1] = buffer[j + 1];
  2426. tempVertexData.positions[j + 2] = buffer[j + 2];
  2427. }
  2428. }
  2429. else {
  2430. tempVertexData.positions = new Float32Array(buffer.length);
  2431. tempVertexData.positions.set(buffer);
  2432. }
  2433. verticesCounts.push(tempVertexData.positions.length);
  2434. }
  2435. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  2436. var channel = Number(semantic.split("_")[1]);
  2437. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  2438. var uvs = new Float32Array(buffer.length);
  2439. uvs.set(buffer);
  2440. normalizeUVs(uvs);
  2441. tempVertexData.set(uvs, uvKind);
  2442. }
  2443. else if (semantic === "JOINT") {
  2444. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  2445. tempVertexData.matricesIndices.set(buffer);
  2446. }
  2447. else if (semantic === "WEIGHT") {
  2448. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  2449. tempVertexData.matricesWeights.set(buffer);
  2450. }
  2451. else if (semantic === "COLOR") {
  2452. tempVertexData.colors = new Float32Array(buffer.length);
  2453. tempVertexData.colors.set(buffer);
  2454. }
  2455. }
  2456. // Indices
  2457. accessor = gltfRuntime.accessors[primitive.indices];
  2458. if (accessor) {
  2459. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  2460. tempVertexData.indices = new Int32Array(buffer.length);
  2461. tempVertexData.indices.set(buffer);
  2462. indexCounts.push(tempVertexData.indices.length);
  2463. }
  2464. else {
  2465. // Set indices on the fly
  2466. var indices = [];
  2467. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  2468. indices.push(j);
  2469. }
  2470. tempVertexData.indices = new Int32Array(indices);
  2471. indexCounts.push(tempVertexData.indices.length);
  2472. }
  2473. if (!vertexData) {
  2474. vertexData = tempVertexData;
  2475. }
  2476. else {
  2477. vertexData.merge(tempVertexData);
  2478. }
  2479. // Sub material
  2480. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  2481. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  2482. // Update vertices start and index start
  2483. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  2484. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  2485. }
  2486. }
  2487. var material;
  2488. if (subMaterials.length > 1) {
  2489. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  2490. material.subMaterials = subMaterials;
  2491. }
  2492. else {
  2493. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  2494. }
  2495. if (subMaterials.length === 1) {
  2496. material = subMaterials[0];
  2497. }
  2498. if (!newMesh.material) {
  2499. newMesh.material = material;
  2500. }
  2501. // Apply geometry
  2502. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  2503. newMesh.computeWorldMatrix(true);
  2504. // Apply submeshes
  2505. newMesh.subMeshes = [];
  2506. var index = 0;
  2507. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  2508. var meshID = meshes[meshIndex];
  2509. var mesh = gltfRuntime.meshes[meshID];
  2510. if (!mesh) {
  2511. continue;
  2512. }
  2513. for (var i = 0; i < mesh.primitives.length; i++) {
  2514. if (mesh.primitives[i].mode !== 4) {
  2515. //continue;
  2516. }
  2517. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  2518. index++;
  2519. }
  2520. }
  2521. // Finish
  2522. return newMesh;
  2523. };
  2524. /**
  2525. * Configure node transformation from position, rotation and scaling
  2526. */
  2527. var configureNode = function (newNode, position, rotation, scaling) {
  2528. if (newNode.position) {
  2529. newNode.position = position;
  2530. }
  2531. if (newNode.rotationQuaternion || newNode.rotation) {
  2532. newNode.rotationQuaternion = rotation;
  2533. }
  2534. if (newNode.scaling) {
  2535. newNode.scaling = scaling;
  2536. }
  2537. };
  2538. /**
  2539. * Configures node from transformation matrix
  2540. */
  2541. var configureNodeFromMatrix = function (newNode, node, parent) {
  2542. if (node.matrix) {
  2543. var position = new BABYLON.Vector3(0, 0, 0);
  2544. var rotation = new BABYLON.Quaternion();
  2545. var scaling = new BABYLON.Vector3(0, 0, 0);
  2546. var mat = BABYLON.Matrix.FromArray(node.matrix);
  2547. mat.decompose(scaling, rotation, position);
  2548. configureNode(newNode, position, rotation, scaling);
  2549. }
  2550. else if (node.translation && node.rotation && node.scale) {
  2551. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  2552. }
  2553. newNode.computeWorldMatrix(true);
  2554. };
  2555. /**
  2556. * Imports a node
  2557. */
  2558. var importNode = function (gltfRuntime, node, id, parent) {
  2559. var lastNode = null;
  2560. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  2561. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  2562. return null;
  2563. }
  2564. }
  2565. // Meshes
  2566. if (node.skin) {
  2567. if (node.meshes) {
  2568. var skin = gltfRuntime.skins[node.skin];
  2569. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  2570. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  2571. if (newMesh.skeleton === null) {
  2572. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  2573. if (!skin.babylonSkeleton) {
  2574. skin.babylonSkeleton = newMesh.skeleton;
  2575. }
  2576. }
  2577. lastNode = newMesh;
  2578. }
  2579. }
  2580. else if (node.meshes) {
  2581. /**
  2582. * Improve meshes property
  2583. */
  2584. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  2585. lastNode = newMesh;
  2586. }
  2587. // Lights
  2588. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  2589. var light = gltfRuntime.lights[node.light];
  2590. if (light) {
  2591. if (light.type === "ambient") {
  2592. var ambienLight = light[light.type];
  2593. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2594. hemiLight.name = node.name || "";
  2595. if (ambienLight.color) {
  2596. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  2597. }
  2598. lastNode = hemiLight;
  2599. }
  2600. else if (light.type === "directional") {
  2601. var directionalLight = light[light.type];
  2602. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2603. dirLight.name = node.name || "";
  2604. if (directionalLight.color) {
  2605. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  2606. }
  2607. lastNode = dirLight;
  2608. }
  2609. else if (light.type === "point") {
  2610. var pointLight = light[light.type];
  2611. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2612. ptLight.name = node.name || "";
  2613. if (pointLight.color) {
  2614. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  2615. }
  2616. lastNode = ptLight;
  2617. }
  2618. else if (light.type === "spot") {
  2619. var spotLight = light[light.type];
  2620. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  2621. spLight.name = node.name || "";
  2622. if (spotLight.color) {
  2623. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  2624. }
  2625. if (spotLight.fallOfAngle) {
  2626. spLight.angle = spotLight.fallOfAngle;
  2627. }
  2628. if (spotLight.fallOffExponent) {
  2629. spLight.exponent = spotLight.fallOffExponent;
  2630. }
  2631. lastNode = spLight;
  2632. }
  2633. }
  2634. }
  2635. // Cameras
  2636. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  2637. var camera = gltfRuntime.cameras[node.camera];
  2638. if (camera) {
  2639. if (camera.type === "orthographic") {
  2640. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  2641. orthoCamera.name = node.name || "";
  2642. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  2643. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  2644. lastNode = orthoCamera;
  2645. }
  2646. else if (camera.type === "perspective") {
  2647. var perspectiveCamera = camera[camera.type];
  2648. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  2649. persCamera.name = node.name || "";
  2650. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  2651. if (!perspectiveCamera.aspectRatio) {
  2652. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  2653. }
  2654. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  2655. persCamera.maxZ = perspectiveCamera.zfar;
  2656. persCamera.minZ = perspectiveCamera.znear;
  2657. }
  2658. lastNode = persCamera;
  2659. }
  2660. }
  2661. }
  2662. // Empty node
  2663. if (!node.jointName) {
  2664. if (node.babylonNode) {
  2665. return node.babylonNode;
  2666. }
  2667. else if (lastNode === null) {
  2668. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  2669. node.babylonNode = dummy;
  2670. lastNode = dummy;
  2671. }
  2672. }
  2673. if (lastNode !== null) {
  2674. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  2675. configureNodeFromMatrix(lastNode, node, parent);
  2676. }
  2677. else {
  2678. var translation = node.translation || [0, 0, 0];
  2679. var rotation = node.rotation || [0, 0, 0, 1];
  2680. var scale = node.scale || [1, 1, 1];
  2681. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  2682. }
  2683. lastNode.updateCache(true);
  2684. node.babylonNode = lastNode;
  2685. }
  2686. return lastNode;
  2687. };
  2688. /**
  2689. * Traverses nodes and creates them
  2690. */
  2691. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  2692. if (meshIncluded === void 0) { meshIncluded = false; }
  2693. var node = gltfRuntime.nodes[id];
  2694. var newNode = null;
  2695. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  2696. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  2697. meshIncluded = true;
  2698. }
  2699. else {
  2700. meshIncluded = false;
  2701. }
  2702. }
  2703. else {
  2704. meshIncluded = true;
  2705. }
  2706. if (!node.jointName && meshIncluded) {
  2707. newNode = importNode(gltfRuntime, node, id, parent);
  2708. if (newNode !== null) {
  2709. newNode.id = id;
  2710. newNode.parent = parent;
  2711. }
  2712. }
  2713. if (node.children) {
  2714. for (var i = 0; i < node.children.length; i++) {
  2715. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  2716. }
  2717. }
  2718. };
  2719. /**
  2720. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  2721. */
  2722. var postLoad = function (gltfRuntime) {
  2723. // Nodes
  2724. var currentScene = gltfRuntime.currentScene;
  2725. if (currentScene) {
  2726. for (var i = 0; i < currentScene.nodes.length; i++) {
  2727. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2728. }
  2729. }
  2730. else {
  2731. for (var thing in gltfRuntime.scenes) {
  2732. currentScene = gltfRuntime.scenes[thing];
  2733. for (var i = 0; i < currentScene.nodes.length; i++) {
  2734. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2735. }
  2736. }
  2737. }
  2738. // Set animations
  2739. loadAnimations(gltfRuntime);
  2740. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  2741. var skeleton = gltfRuntime.scene.skeletons[i];
  2742. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  2743. }
  2744. };
  2745. /**
  2746. * onBind shaderrs callback to set uniforms and matrices
  2747. */
  2748. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  2749. var materialValues = material.values || technique.parameters;
  2750. for (var unif in unTreatedUniforms) {
  2751. var uniform = unTreatedUniforms[unif];
  2752. var type = uniform.type;
  2753. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  2754. if (uniform.semantic && !uniform.source && !uniform.node) {
  2755. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  2756. }
  2757. else if (uniform.semantic && (uniform.source || uniform.node)) {
  2758. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  2759. if (source === null) {
  2760. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  2761. }
  2762. if (source === null) {
  2763. continue;
  2764. }
  2765. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  2766. }
  2767. }
  2768. else {
  2769. var value = materialValues[technique.uniforms[unif]];
  2770. if (!value) {
  2771. continue;
  2772. }
  2773. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  2774. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  2775. if (texture === null || texture === undefined) {
  2776. continue;
  2777. }
  2778. shaderMaterial.getEffect().setTexture(unif, texture);
  2779. }
  2780. else {
  2781. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  2782. }
  2783. }
  2784. }
  2785. onSuccess(shaderMaterial);
  2786. };
  2787. /**
  2788. * Prepare uniforms to send the only one time
  2789. * Loads the appropriate textures
  2790. */
  2791. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  2792. var materialValues = material.values || technique.parameters;
  2793. var techniqueUniforms = technique.uniforms;
  2794. /**
  2795. * Prepare values here (not matrices)
  2796. */
  2797. for (var unif in unTreatedUniforms) {
  2798. var uniform = unTreatedUniforms[unif];
  2799. var type = uniform.type;
  2800. var value = materialValues[techniqueUniforms[unif]];
  2801. if (value === undefined) {
  2802. // In case the value is the same for all materials
  2803. value = uniform.value;
  2804. }
  2805. if (!value) {
  2806. continue;
  2807. }
  2808. var onLoadTexture = function (uniformName) {
  2809. return function (texture) {
  2810. if (uniform.value && uniformName) {
  2811. // Static uniform
  2812. shaderMaterial.setTexture(uniformName, texture);
  2813. delete unTreatedUniforms[uniformName];
  2814. }
  2815. };
  2816. };
  2817. // Texture (sampler2D)
  2818. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  2819. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  2820. }
  2821. // Others
  2822. else {
  2823. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  2824. // Static uniform
  2825. delete unTreatedUniforms[unif];
  2826. }
  2827. }
  2828. }
  2829. };
  2830. /**
  2831. * Shader compilation failed
  2832. */
  2833. var onShaderCompileError = function (program, shaderMaterial, onError) {
  2834. return function (effect, error) {
  2835. shaderMaterial.dispose(true);
  2836. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  2837. };
  2838. };
  2839. /**
  2840. * Shader compilation success
  2841. */
  2842. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  2843. return function (_) {
  2844. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  2845. shaderMaterial.onBind = function (mesh) {
  2846. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  2847. };
  2848. };
  2849. };
  2850. /**
  2851. * Returns the appropriate uniform if already handled by babylon
  2852. */
  2853. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  2854. for (var unif in technique.uniforms) {
  2855. var uniform = technique.uniforms[unif];
  2856. var uniformParameter = technique.parameters[uniform];
  2857. if (tokenizer.currentIdentifier === unif) {
  2858. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  2859. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  2860. if (transformIndex !== -1) {
  2861. delete unTreatedUniforms[unif];
  2862. return babylonTransforms[transformIndex];
  2863. }
  2864. }
  2865. }
  2866. }
  2867. return tokenizer.currentIdentifier;
  2868. };
  2869. /**
  2870. * All shaders loaded. Create materials one by one
  2871. */
  2872. var importMaterials = function (gltfRuntime) {
  2873. // Create materials
  2874. for (var mat in gltfRuntime.materials) {
  2875. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  2876. }
  2877. };
  2878. /**
  2879. * Implementation of the base glTF spec
  2880. */
  2881. var GLTFLoaderBase = /** @class */ (function () {
  2882. function GLTFLoaderBase() {
  2883. }
  2884. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  2885. var gltfRuntime = {
  2886. extensions: {},
  2887. accessors: {},
  2888. buffers: {},
  2889. bufferViews: {},
  2890. meshes: {},
  2891. lights: {},
  2892. cameras: {},
  2893. nodes: {},
  2894. images: {},
  2895. textures: {},
  2896. shaders: {},
  2897. programs: {},
  2898. samplers: {},
  2899. techniques: {},
  2900. materials: {},
  2901. animations: {},
  2902. skins: {},
  2903. extensionsUsed: [],
  2904. scenes: {},
  2905. buffersCount: 0,
  2906. shaderscount: 0,
  2907. scene: scene,
  2908. rootUrl: rootUrl,
  2909. loadedBufferCount: 0,
  2910. loadedBufferViews: {},
  2911. loadedShaderCount: 0,
  2912. importOnlyMeshes: false,
  2913. dummyNodes: []
  2914. };
  2915. // Parse
  2916. if (parsedData.extensions) {
  2917. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  2918. }
  2919. if (parsedData.extensionsUsed) {
  2920. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  2921. }
  2922. if (parsedData.buffers) {
  2923. parseBuffers(parsedData.buffers, gltfRuntime);
  2924. }
  2925. if (parsedData.bufferViews) {
  2926. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  2927. }
  2928. if (parsedData.accessors) {
  2929. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  2930. }
  2931. if (parsedData.meshes) {
  2932. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  2933. }
  2934. if (parsedData.lights) {
  2935. parseObject(parsedData.lights, "lights", gltfRuntime);
  2936. }
  2937. if (parsedData.cameras) {
  2938. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  2939. }
  2940. if (parsedData.nodes) {
  2941. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  2942. }
  2943. if (parsedData.images) {
  2944. parseObject(parsedData.images, "images", gltfRuntime);
  2945. }
  2946. if (parsedData.textures) {
  2947. parseObject(parsedData.textures, "textures", gltfRuntime);
  2948. }
  2949. if (parsedData.shaders) {
  2950. parseShaders(parsedData.shaders, gltfRuntime);
  2951. }
  2952. if (parsedData.programs) {
  2953. parseObject(parsedData.programs, "programs", gltfRuntime);
  2954. }
  2955. if (parsedData.samplers) {
  2956. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  2957. }
  2958. if (parsedData.techniques) {
  2959. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  2960. }
  2961. if (parsedData.materials) {
  2962. parseObject(parsedData.materials, "materials", gltfRuntime);
  2963. }
  2964. if (parsedData.animations) {
  2965. parseObject(parsedData.animations, "animations", gltfRuntime);
  2966. }
  2967. if (parsedData.skins) {
  2968. parseObject(parsedData.skins, "skins", gltfRuntime);
  2969. }
  2970. if (parsedData.scenes) {
  2971. gltfRuntime.scenes = parsedData.scenes;
  2972. }
  2973. if (parsedData.scene && parsedData.scenes) {
  2974. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  2975. }
  2976. return gltfRuntime;
  2977. };
  2978. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2979. var buffer = gltfRuntime.buffers[id];
  2980. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  2981. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  2982. }
  2983. else {
  2984. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  2985. if (request) {
  2986. onError(request.status + " " + request.statusText);
  2987. }
  2988. });
  2989. }
  2990. };
  2991. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2992. var texture = gltfRuntime.textures[id];
  2993. if (!texture || !texture.source) {
  2994. onError("");
  2995. return;
  2996. }
  2997. if (texture.babylonTexture) {
  2998. onSuccess(null);
  2999. return;
  3000. }
  3001. var source = gltfRuntime.images[texture.source];
  3002. if (BABYLON.Tools.IsBase64(source.uri)) {
  3003. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  3004. }
  3005. else {
  3006. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  3007. if (request) {
  3008. onError(request.status + " " + request.statusText);
  3009. }
  3010. });
  3011. }
  3012. };
  3013. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  3014. var texture = gltfRuntime.textures[id];
  3015. if (texture.babylonTexture) {
  3016. onSuccess(texture.babylonTexture);
  3017. return;
  3018. }
  3019. var sampler = gltfRuntime.samplers[texture.sampler];
  3020. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  3021. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  3022. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  3023. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  3024. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  3025. var blob = buffer == null ? new Blob() : new Blob([buffer]);
  3026. var blobURL = URL.createObjectURL(blob);
  3027. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  3028. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  3029. if (sampler.wrapS !== undefined) {
  3030. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  3031. }
  3032. if (sampler.wrapT !== undefined) {
  3033. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  3034. }
  3035. newTexture.name = id;
  3036. texture.babylonTexture = newTexture;
  3037. onSuccess(newTexture);
  3038. };
  3039. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  3040. var shader = gltfRuntime.shaders[id];
  3041. if (BABYLON.Tools.IsBase64(shader.uri)) {
  3042. var shaderString = atob(shader.uri.split(",")[1]);
  3043. if (onSuccess) {
  3044. onSuccess(shaderString);
  3045. }
  3046. }
  3047. else {
  3048. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  3049. if (request && onError) {
  3050. onError(request.status + " " + request.statusText);
  3051. }
  3052. });
  3053. }
  3054. };
  3055. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3056. var material = gltfRuntime.materials[id];
  3057. if (!material.technique) {
  3058. if (onError) {
  3059. onError("No technique found.");
  3060. }
  3061. return;
  3062. }
  3063. var technique = gltfRuntime.techniques[material.technique];
  3064. if (!technique) {
  3065. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  3066. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  3067. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  3068. onSuccess(defaultMaterial);
  3069. return;
  3070. }
  3071. var program = gltfRuntime.programs[technique.program];
  3072. var states = technique.states;
  3073. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  3074. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  3075. var newVertexShader = "";
  3076. var newPixelShader = "";
  3077. var vertexTokenizer = new Tokenizer(vertexShader);
  3078. var pixelTokenizer = new Tokenizer(pixelShader);
  3079. var unTreatedUniforms = {};
  3080. var uniforms = [];
  3081. var attributes = [];
  3082. var samplers = [];
  3083. // Fill uniform, sampler2D and attributes
  3084. for (var unif in technique.uniforms) {
  3085. var uniform = technique.uniforms[unif];
  3086. var uniformParameter = technique.parameters[uniform];
  3087. unTreatedUniforms[unif] = uniformParameter;
  3088. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  3089. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  3090. if (transformIndex !== -1) {
  3091. uniforms.push(babylonTransforms[transformIndex]);
  3092. delete unTreatedUniforms[unif];
  3093. }
  3094. else {
  3095. uniforms.push(unif);
  3096. }
  3097. }
  3098. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  3099. samplers.push(unif);
  3100. }
  3101. else {
  3102. uniforms.push(unif);
  3103. }
  3104. }
  3105. for (var attr in technique.attributes) {
  3106. var attribute = technique.attributes[attr];
  3107. var attributeParameter = technique.parameters[attribute];
  3108. if (attributeParameter.semantic) {
  3109. var name_1 = getAttribute(attributeParameter);
  3110. if (name_1) {
  3111. attributes.push(name_1);
  3112. }
  3113. }
  3114. }
  3115. // Configure vertex shader
  3116. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  3117. var tokenType = vertexTokenizer.currentToken;
  3118. if (tokenType !== ETokenType.IDENTIFIER) {
  3119. newVertexShader += vertexTokenizer.currentString;
  3120. continue;
  3121. }
  3122. var foundAttribute = false;
  3123. for (var attr in technique.attributes) {
  3124. var attribute = technique.attributes[attr];
  3125. var attributeParameter = technique.parameters[attribute];
  3126. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  3127. newVertexShader += getAttribute(attributeParameter);
  3128. foundAttribute = true;
  3129. break;
  3130. }
  3131. }
  3132. if (foundAttribute) {
  3133. continue;
  3134. }
  3135. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  3136. }
  3137. // Configure pixel shader
  3138. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  3139. var tokenType = pixelTokenizer.currentToken;
  3140. if (tokenType !== ETokenType.IDENTIFIER) {
  3141. newPixelShader += pixelTokenizer.currentString;
  3142. continue;
  3143. }
  3144. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  3145. }
  3146. // Create shader material
  3147. var shaderPath = {
  3148. vertex: program.vertexShader + id,
  3149. fragment: program.fragmentShader + id
  3150. };
  3151. var options = {
  3152. attributes: attributes,
  3153. uniforms: uniforms,
  3154. samplers: samplers,
  3155. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  3156. };
  3157. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  3158. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  3159. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  3160. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  3161. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  3162. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  3163. if (states && states.functions) {
  3164. var functions = states.functions;
  3165. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  3166. shaderMaterial.backFaceCulling = false;
  3167. }
  3168. var blendFunc = functions.blendFuncSeparate;
  3169. if (blendFunc) {
  3170. 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) {
  3171. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  3172. }
  3173. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  3174. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  3175. }
  3176. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  3177. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  3178. }
  3179. 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) {
  3180. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  3181. }
  3182. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  3183. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  3184. }
  3185. 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) {
  3186. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  3187. }
  3188. }
  3189. }
  3190. };
  3191. return GLTFLoaderBase;
  3192. }());
  3193. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  3194. /**
  3195. * glTF V1 Loader
  3196. */
  3197. var GLTFLoader = /** @class */ (function () {
  3198. function GLTFLoader() {
  3199. this.state = null;
  3200. }
  3201. GLTFLoader.RegisterExtension = function (extension) {
  3202. if (GLTFLoader.Extensions[extension.name]) {
  3203. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  3204. return;
  3205. }
  3206. GLTFLoader.Extensions[extension.name] = extension;
  3207. };
  3208. GLTFLoader.prototype.dispose = function () {
  3209. // do nothing
  3210. };
  3211. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  3212. var _this = this;
  3213. scene.useRightHandedSystem = true;
  3214. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  3215. gltfRuntime.importOnlyMeshes = true;
  3216. if (meshesNames === "") {
  3217. gltfRuntime.importMeshesNames = [];
  3218. }
  3219. else if (typeof meshesNames === "string") {
  3220. gltfRuntime.importMeshesNames = [meshesNames];
  3221. }
  3222. else if (meshesNames && !(meshesNames instanceof Array)) {
  3223. gltfRuntime.importMeshesNames = [meshesNames];
  3224. }
  3225. else {
  3226. gltfRuntime.importMeshesNames = [];
  3227. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  3228. }
  3229. // Create nodes
  3230. _this._createNodes(gltfRuntime);
  3231. var meshes = new Array();
  3232. var skeletons = new Array();
  3233. // Fill arrays of meshes and skeletons
  3234. for (var nde in gltfRuntime.nodes) {
  3235. var node = gltfRuntime.nodes[nde];
  3236. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  3237. meshes.push(node.babylonNode);
  3238. }
  3239. }
  3240. for (var skl in gltfRuntime.skins) {
  3241. var skin = gltfRuntime.skins[skl];
  3242. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  3243. skeletons.push(skin.babylonSkeleton);
  3244. }
  3245. }
  3246. // Load buffers, shaders, materials, etc.
  3247. _this._loadBuffersAsync(gltfRuntime, function () {
  3248. _this._loadShadersAsync(gltfRuntime, function () {
  3249. importMaterials(gltfRuntime);
  3250. postLoad(gltfRuntime);
  3251. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  3252. onSuccess(meshes, skeletons);
  3253. }
  3254. });
  3255. }, onProgress);
  3256. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  3257. onSuccess(meshes, skeletons);
  3258. }
  3259. }, onError);
  3260. return true;
  3261. };
  3262. /**
  3263. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  3264. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  3265. * @param scene the scene the meshes should be added to
  3266. * @param data gltf data containing information of the meshes in a loaded file
  3267. * @param rootUrl root url to load from
  3268. * @param onProgress event that fires when loading progress has occured
  3269. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  3270. */
  3271. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  3272. var _this = this;
  3273. return new Promise(function (resolve, reject) {
  3274. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  3275. resolve({
  3276. meshes: meshes,
  3277. particleSystems: [],
  3278. skeletons: skeletons,
  3279. animationGroups: []
  3280. });
  3281. }, onProgress, function (message) {
  3282. reject(new Error(message));
  3283. });
  3284. });
  3285. };
  3286. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  3287. var _this = this;
  3288. scene.useRightHandedSystem = true;
  3289. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  3290. // Load runtime extensios
  3291. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  3292. // Create nodes
  3293. _this._createNodes(gltfRuntime);
  3294. // Load buffers, shaders, materials, etc.
  3295. _this._loadBuffersAsync(gltfRuntime, function () {
  3296. _this._loadShadersAsync(gltfRuntime, function () {
  3297. importMaterials(gltfRuntime);
  3298. postLoad(gltfRuntime);
  3299. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  3300. onSuccess();
  3301. }
  3302. });
  3303. });
  3304. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  3305. onSuccess();
  3306. }
  3307. }, onError);
  3308. }, onError);
  3309. };
  3310. /**
  3311. * Imports all objects from a loaded gltf file and adds them to the scene
  3312. * @param scene the scene the objects should be added to
  3313. * @param data gltf data containing information of the meshes in a loaded file
  3314. * @param rootUrl root url to load from
  3315. * @param onProgress event that fires when loading progress has occured
  3316. * @returns a promise which completes when objects have been loaded to the scene
  3317. */
  3318. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  3319. var _this = this;
  3320. return new Promise(function (resolve, reject) {
  3321. _this._loadAsync(scene, data, rootUrl, function () {
  3322. resolve();
  3323. }, onProgress, function (message) {
  3324. reject(new Error(message));
  3325. });
  3326. });
  3327. };
  3328. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  3329. var hasShaders = false;
  3330. var processShader = function (sha, shader) {
  3331. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  3332. if (shaderString instanceof ArrayBuffer) {
  3333. return;
  3334. }
  3335. gltfRuntime.loadedShaderCount++;
  3336. if (shaderString) {
  3337. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  3338. }
  3339. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  3340. onload();
  3341. }
  3342. }, function () {
  3343. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  3344. });
  3345. };
  3346. for (var sha in gltfRuntime.shaders) {
  3347. hasShaders = true;
  3348. var shader = gltfRuntime.shaders[sha];
  3349. if (shader) {
  3350. processShader.bind(this, sha, shader)();
  3351. }
  3352. else {
  3353. BABYLON.Tools.Error("No shader named: " + sha);
  3354. }
  3355. }
  3356. if (!hasShaders) {
  3357. onload();
  3358. }
  3359. };
  3360. ;
  3361. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  3362. var hasBuffers = false;
  3363. var processBuffer = function (buf, buffer) {
  3364. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  3365. gltfRuntime.loadedBufferCount++;
  3366. if (bufferView) {
  3367. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  3368. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  3369. }
  3370. gltfRuntime.loadedBufferViews[buf] = bufferView;
  3371. }
  3372. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  3373. onLoad();
  3374. }
  3375. }, function () {
  3376. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  3377. });
  3378. };
  3379. for (var buf in gltfRuntime.buffers) {
  3380. hasBuffers = true;
  3381. var buffer = gltfRuntime.buffers[buf];
  3382. if (buffer) {
  3383. processBuffer.bind(this, buf, buffer)();
  3384. }
  3385. else {
  3386. BABYLON.Tools.Error("No buffer named: " + buf);
  3387. }
  3388. }
  3389. if (!hasBuffers) {
  3390. onLoad();
  3391. }
  3392. };
  3393. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  3394. var currentScene = gltfRuntime.currentScene;
  3395. if (currentScene) {
  3396. // Only one scene even if multiple scenes are defined
  3397. for (var i = 0; i < currentScene.nodes.length; i++) {
  3398. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  3399. }
  3400. }
  3401. else {
  3402. // Load all scenes
  3403. for (var thing in gltfRuntime.scenes) {
  3404. currentScene = gltfRuntime.scenes[thing];
  3405. for (var i = 0; i < currentScene.nodes.length; i++) {
  3406. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  3407. }
  3408. }
  3409. }
  3410. };
  3411. GLTFLoader.Extensions = {};
  3412. return GLTFLoader;
  3413. }());
  3414. GLTF1.GLTFLoader = GLTFLoader;
  3415. ;
  3416. BABYLON.GLTFFileLoader._CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  3417. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3418. })(BABYLON || (BABYLON = {}));
  3419. //# sourceMappingURL=babylon.glTFLoader.js.map
  3420. var BABYLON;
  3421. (function (BABYLON) {
  3422. var GLTF1;
  3423. (function (GLTF1) {
  3424. /**
  3425. * Utils functions for GLTF
  3426. */
  3427. var GLTFUtils = /** @class */ (function () {
  3428. function GLTFUtils() {
  3429. }
  3430. /**
  3431. * Sets the given "parameter" matrix
  3432. * @param scene: the Scene object
  3433. * @param source: the source node where to pick the matrix
  3434. * @param parameter: the GLTF technique parameter
  3435. * @param uniformName: the name of the shader's uniform
  3436. * @param shaderMaterial: the shader material
  3437. */
  3438. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  3439. var mat = null;
  3440. if (parameter.semantic === "MODEL") {
  3441. mat = source.getWorldMatrix();
  3442. }
  3443. else if (parameter.semantic === "PROJECTION") {
  3444. mat = scene.getProjectionMatrix();
  3445. }
  3446. else if (parameter.semantic === "VIEW") {
  3447. mat = scene.getViewMatrix();
  3448. }
  3449. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  3450. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  3451. }
  3452. else if (parameter.semantic === "MODELVIEW") {
  3453. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  3454. }
  3455. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  3456. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  3457. }
  3458. else if (parameter.semantic === "MODELINVERSE") {
  3459. mat = source.getWorldMatrix().invert();
  3460. }
  3461. else if (parameter.semantic === "VIEWINVERSE") {
  3462. mat = scene.getViewMatrix().invert();
  3463. }
  3464. else if (parameter.semantic === "PROJECTIONINVERSE") {
  3465. mat = scene.getProjectionMatrix().invert();
  3466. }
  3467. else if (parameter.semantic === "MODELVIEWINVERSE") {
  3468. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  3469. }
  3470. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  3471. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  3472. }
  3473. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  3474. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  3475. }
  3476. else {
  3477. debugger;
  3478. }
  3479. if (mat) {
  3480. switch (parameter.type) {
  3481. case GLTF1.EParameterType.FLOAT_MAT2:
  3482. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  3483. break;
  3484. case GLTF1.EParameterType.FLOAT_MAT3:
  3485. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  3486. break;
  3487. case GLTF1.EParameterType.FLOAT_MAT4:
  3488. shaderMaterial.setMatrix(uniformName, mat);
  3489. break;
  3490. default: break;
  3491. }
  3492. }
  3493. };
  3494. /**
  3495. * Sets the given "parameter" matrix
  3496. * @param shaderMaterial: the shader material
  3497. * @param uniform: the name of the shader's uniform
  3498. * @param value: the value of the uniform
  3499. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  3500. */
  3501. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  3502. switch (type) {
  3503. case GLTF1.EParameterType.FLOAT:
  3504. shaderMaterial.setFloat(uniform, value);
  3505. return true;
  3506. case GLTF1.EParameterType.FLOAT_VEC2:
  3507. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  3508. return true;
  3509. case GLTF1.EParameterType.FLOAT_VEC3:
  3510. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  3511. return true;
  3512. case GLTF1.EParameterType.FLOAT_VEC4:
  3513. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  3514. return true;
  3515. default: return false;
  3516. }
  3517. };
  3518. /**
  3519. * Returns the wrap mode of the texture
  3520. * @param mode: the mode value
  3521. */
  3522. GLTFUtils.GetWrapMode = function (mode) {
  3523. switch (mode) {
  3524. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  3525. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  3526. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  3527. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  3528. }
  3529. };
  3530. /**
  3531. * Returns the byte stride giving an accessor
  3532. * @param accessor: the GLTF accessor objet
  3533. */
  3534. GLTFUtils.GetByteStrideFromType = function (accessor) {
  3535. // Needs this function since "byteStride" isn't requiered in glTF format
  3536. var type = accessor.type;
  3537. switch (type) {
  3538. case "VEC2": return 2;
  3539. case "VEC3": return 3;
  3540. case "VEC4": return 4;
  3541. case "MAT2": return 4;
  3542. case "MAT3": return 9;
  3543. case "MAT4": return 16;
  3544. default: return 1;
  3545. }
  3546. };
  3547. /**
  3548. * Returns the texture filter mode giving a mode value
  3549. * @param mode: the filter mode value
  3550. */
  3551. GLTFUtils.GetTextureFilterMode = function (mode) {
  3552. switch (mode) {
  3553. case GLTF1.ETextureFilterType.LINEAR:
  3554. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  3555. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3556. case GLTF1.ETextureFilterType.NEAREST:
  3557. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  3558. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  3559. }
  3560. };
  3561. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  3562. var byteOffset = bufferView.byteOffset + byteOffset;
  3563. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  3564. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  3565. throw new Error("Buffer access is out of range");
  3566. }
  3567. var buffer = loadedBufferView.buffer;
  3568. byteOffset += loadedBufferView.byteOffset;
  3569. switch (componentType) {
  3570. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  3571. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  3572. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  3573. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  3574. default: return new Float32Array(buffer, byteOffset, byteLength);
  3575. }
  3576. };
  3577. /**
  3578. * Returns a buffer from its accessor
  3579. * @param gltfRuntime: the GLTF runtime
  3580. * @param accessor: the GLTF accessor
  3581. */
  3582. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  3583. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  3584. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  3585. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  3586. };
  3587. /**
  3588. * Decodes a buffer view into a string
  3589. * @param view: the buffer view
  3590. */
  3591. GLTFUtils.DecodeBufferToText = function (view) {
  3592. var result = "";
  3593. var length = view.byteLength;
  3594. for (var i = 0; i < length; ++i) {
  3595. result += String.fromCharCode(view[i]);
  3596. }
  3597. return result;
  3598. };
  3599. /**
  3600. * Returns the default material of gltf. Related to
  3601. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  3602. * @param scene: the Babylon.js scene
  3603. */
  3604. GLTFUtils.GetDefaultMaterial = function (scene) {
  3605. if (!GLTFUtils._DefaultMaterial) {
  3606. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  3607. "precision highp float;",
  3608. "",
  3609. "uniform mat4 worldView;",
  3610. "uniform mat4 projection;",
  3611. "",
  3612. "attribute vec3 position;",
  3613. "",
  3614. "void main(void)",
  3615. "{",
  3616. " gl_Position = projection * worldView * vec4(position, 1.0);",
  3617. "}"
  3618. ].join("\n");
  3619. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  3620. "precision highp float;",
  3621. "",
  3622. "uniform vec4 u_emission;",
  3623. "",
  3624. "void main(void)",
  3625. "{",
  3626. " gl_FragColor = u_emission;",
  3627. "}"
  3628. ].join("\n");
  3629. var shaderPath = {
  3630. vertex: "GLTFDefaultMaterial",
  3631. fragment: "GLTFDefaultMaterial"
  3632. };
  3633. var options = {
  3634. attributes: ["position"],
  3635. uniforms: ["worldView", "projection", "u_emission"],
  3636. samplers: new Array(),
  3637. needAlphaBlending: false
  3638. };
  3639. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  3640. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  3641. }
  3642. return GLTFUtils._DefaultMaterial;
  3643. };
  3644. // The GLTF default material
  3645. GLTFUtils._DefaultMaterial = null;
  3646. return GLTFUtils;
  3647. }());
  3648. GLTF1.GLTFUtils = GLTFUtils;
  3649. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3650. })(BABYLON || (BABYLON = {}));
  3651. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  3652. var BABYLON;
  3653. (function (BABYLON) {
  3654. var GLTF1;
  3655. (function (GLTF1) {
  3656. var GLTFLoaderExtension = /** @class */ (function () {
  3657. function GLTFLoaderExtension(name) {
  3658. this._name = name;
  3659. }
  3660. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  3661. get: function () {
  3662. return this._name;
  3663. },
  3664. enumerable: true,
  3665. configurable: true
  3666. });
  3667. /**
  3668. * Defines an override for loading the runtime
  3669. * Return true to stop further extensions from loading the runtime
  3670. */
  3671. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  3672. return false;
  3673. };
  3674. /**
  3675. * Defines an onverride for creating gltf runtime
  3676. * Return true to stop further extensions from creating the runtime
  3677. */
  3678. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  3679. return false;
  3680. };
  3681. /**
  3682. * Defines an override for loading buffers
  3683. * Return true to stop further extensions from loading this buffer
  3684. */
  3685. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  3686. return false;
  3687. };
  3688. /**
  3689. * Defines an override for loading texture buffers
  3690. * Return true to stop further extensions from loading this texture data
  3691. */
  3692. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3693. return false;
  3694. };
  3695. /**
  3696. * Defines an override for creating textures
  3697. * Return true to stop further extensions from loading this texture
  3698. */
  3699. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  3700. return false;
  3701. };
  3702. /**
  3703. * Defines an override for loading shader strings
  3704. * Return true to stop further extensions from loading this shader data
  3705. */
  3706. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  3707. return false;
  3708. };
  3709. /**
  3710. * Defines an override for loading materials
  3711. * Return true to stop further extensions from loading this material
  3712. */
  3713. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3714. return false;
  3715. };
  3716. // ---------
  3717. // Utilities
  3718. // ---------
  3719. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  3720. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3721. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  3722. }, function () {
  3723. setTimeout(function () {
  3724. if (!onSuccess) {
  3725. return;
  3726. }
  3727. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  3728. });
  3729. });
  3730. };
  3731. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  3732. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3733. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  3734. }, function () {
  3735. setTimeout(function () {
  3736. onSuccess();
  3737. });
  3738. });
  3739. };
  3740. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  3741. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3742. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  3743. }, function () {
  3744. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  3745. });
  3746. };
  3747. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  3748. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  3749. if (buffer) {
  3750. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  3751. }
  3752. }, onError);
  3753. };
  3754. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  3755. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3756. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  3757. }, function () {
  3758. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  3759. });
  3760. };
  3761. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3762. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3763. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  3764. }, function () {
  3765. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  3766. });
  3767. };
  3768. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3769. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3770. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  3771. }, function () {
  3772. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  3773. });
  3774. };
  3775. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  3776. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3777. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  3778. }, function () {
  3779. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  3780. });
  3781. };
  3782. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  3783. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  3784. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  3785. if (func(loaderExtension)) {
  3786. return;
  3787. }
  3788. }
  3789. defaultFunc();
  3790. };
  3791. return GLTFLoaderExtension;
  3792. }());
  3793. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  3794. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3795. })(BABYLON || (BABYLON = {}));
  3796. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  3797. var BABYLON;
  3798. (function (BABYLON) {
  3799. var GLTF1;
  3800. (function (GLTF1) {
  3801. var BinaryExtensionBufferName = "binary_glTF";
  3802. var GLTFBinaryExtension = /** @class */ (function (_super) {
  3803. __extends(GLTFBinaryExtension, _super);
  3804. function GLTFBinaryExtension() {
  3805. return _super.call(this, "KHR_binary_glTF") || this;
  3806. }
  3807. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  3808. var extensionsUsed = data.json.extensionsUsed;
  3809. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  3810. return false;
  3811. }
  3812. this._bin = data.bin;
  3813. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  3814. return true;
  3815. };
  3816. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3817. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  3818. return false;
  3819. }
  3820. if (id !== BinaryExtensionBufferName) {
  3821. return false;
  3822. }
  3823. onSuccess(this._bin);
  3824. return true;
  3825. };
  3826. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3827. var texture = gltfRuntime.textures[id];
  3828. var source = gltfRuntime.images[texture.source];
  3829. if (!source.extensions || !(this.name in source.extensions)) {
  3830. return false;
  3831. }
  3832. var sourceExt = source.extensions[this.name];
  3833. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  3834. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  3835. onSuccess(buffer);
  3836. return true;
  3837. };
  3838. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  3839. var shader = gltfRuntime.shaders[id];
  3840. if (!shader.extensions || !(this.name in shader.extensions)) {
  3841. return false;
  3842. }
  3843. var binaryExtensionShader = shader.extensions[this.name];
  3844. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  3845. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  3846. setTimeout(function () {
  3847. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  3848. onSuccess(shaderString);
  3849. });
  3850. return true;
  3851. };
  3852. return GLTFBinaryExtension;
  3853. }(GLTF1.GLTFLoaderExtension));
  3854. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  3855. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  3856. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3857. })(BABYLON || (BABYLON = {}));
  3858. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  3859. var BABYLON;
  3860. (function (BABYLON) {
  3861. var GLTF1;
  3862. (function (GLTF1) {
  3863. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  3864. __extends(GLTFMaterialsCommonExtension, _super);
  3865. function GLTFMaterialsCommonExtension() {
  3866. return _super.call(this, "KHR_materials_common") || this;
  3867. }
  3868. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  3869. if (!gltfRuntime.extensions) {
  3870. return false;
  3871. }
  3872. var extension = gltfRuntime.extensions[this.name];
  3873. if (!extension) {
  3874. return false;
  3875. }
  3876. // Create lights
  3877. var lights = extension.lights;
  3878. if (lights) {
  3879. for (var thing in lights) {
  3880. var light = lights[thing];
  3881. switch (light.type) {
  3882. case "ambient":
  3883. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  3884. var ambient = light.ambient;
  3885. if (ambient) {
  3886. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  3887. }
  3888. break;
  3889. case "point":
  3890. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  3891. var point = light.point;
  3892. if (point) {
  3893. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  3894. }
  3895. break;
  3896. case "directional":
  3897. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  3898. var directional = light.directional;
  3899. if (directional) {
  3900. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  3901. }
  3902. break;
  3903. case "spot":
  3904. var spot = light.spot;
  3905. if (spot) {
  3906. 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);
  3907. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  3908. }
  3909. break;
  3910. default:
  3911. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  3912. break;
  3913. }
  3914. }
  3915. }
  3916. return false;
  3917. };
  3918. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3919. var material = gltfRuntime.materials[id];
  3920. if (!material || !material.extensions) {
  3921. return false;
  3922. }
  3923. var extension = material.extensions[this.name];
  3924. if (!extension) {
  3925. return false;
  3926. }
  3927. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  3928. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  3929. if (extension.technique === "CONSTANT") {
  3930. standardMaterial.disableLighting = true;
  3931. }
  3932. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  3933. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  3934. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  3935. // Ambient
  3936. if (typeof extension.values.ambient === "string") {
  3937. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  3938. }
  3939. else {
  3940. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  3941. }
  3942. // Diffuse
  3943. if (typeof extension.values.diffuse === "string") {
  3944. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  3945. }
  3946. else {
  3947. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  3948. }
  3949. // Emission
  3950. if (typeof extension.values.emission === "string") {
  3951. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  3952. }
  3953. else {
  3954. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  3955. }
  3956. // Specular
  3957. if (typeof extension.values.specular === "string") {
  3958. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  3959. }
  3960. else {
  3961. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  3962. }
  3963. return true;
  3964. };
  3965. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  3966. // Create buffer from texture url
  3967. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  3968. // Create texture from buffer
  3969. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  3970. }, onError);
  3971. };
  3972. return GLTFMaterialsCommonExtension;
  3973. }(GLTF1.GLTFLoaderExtension));
  3974. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  3975. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  3976. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3977. })(BABYLON || (BABYLON = {}));
  3978. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  3979. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  3980. /**
  3981. * Defines the module for importing and exporting glTF 2.0 assets
  3982. */
  3983. var BABYLON;
  3984. (function (BABYLON) {
  3985. var GLTF2;
  3986. (function (GLTF2) {
  3987. /**
  3988. * Helper class for working with arrays when loading the glTF asset
  3989. */
  3990. var ArrayItem = /** @class */ (function () {
  3991. function ArrayItem() {
  3992. }
  3993. /**
  3994. * Gets an item from the given array.
  3995. * @param context The context when loading the asset
  3996. * @param array The array to get the item from
  3997. * @param index The index to the array
  3998. * @returns The array item
  3999. */
  4000. ArrayItem.Get = function (context, array, index) {
  4001. if (!array || index == undefined || !array[index]) {
  4002. throw new Error(context + ": Failed to find index (" + index + ")");
  4003. }
  4004. return array[index];
  4005. };
  4006. /**
  4007. * Assign an `index` field to each item of the given array.
  4008. * @param array The array of items
  4009. */
  4010. ArrayItem.Assign = function (array) {
  4011. if (array) {
  4012. for (var index = 0; index < array.length; index++) {
  4013. array[index].index = index;
  4014. }
  4015. }
  4016. };
  4017. return ArrayItem;
  4018. }());
  4019. GLTF2.ArrayItem = ArrayItem;
  4020. /**
  4021. * The glTF 2.0 loader
  4022. */
  4023. var GLTFLoader = /** @class */ (function () {
  4024. /** @hidden */
  4025. function GLTFLoader(parent) {
  4026. /** @hidden */
  4027. this._completePromises = new Array();
  4028. this._disposed = false;
  4029. this._state = null;
  4030. this._extensions = {};
  4031. this._defaultBabylonMaterialData = {};
  4032. this._requests = new Array();
  4033. this._parent = parent;
  4034. }
  4035. /**
  4036. * Registers a loader extension.
  4037. * @param name The name of the loader extension.
  4038. * @param factory The factory function that creates the loader extension.
  4039. */
  4040. GLTFLoader.RegisterExtension = function (name, factory) {
  4041. if (GLTFLoader.UnregisterExtension(name)) {
  4042. BABYLON.Tools.Warn("Extension with the name '" + name + "' already exists");
  4043. }
  4044. GLTFLoader._ExtensionFactories[name] = factory;
  4045. // Keep the order of registration so that extensions registered first are called first.
  4046. GLTFLoader._ExtensionNames.push(name);
  4047. };
  4048. /**
  4049. * Unregisters a loader extension.
  4050. * @param name The name of the loader extenion.
  4051. * @returns A boolean indicating whether the extension has been unregistered
  4052. */
  4053. GLTFLoader.UnregisterExtension = function (name) {
  4054. if (!GLTFLoader._ExtensionFactories[name]) {
  4055. return false;
  4056. }
  4057. delete GLTFLoader._ExtensionFactories[name];
  4058. var index = GLTFLoader._ExtensionNames.indexOf(name);
  4059. if (index !== -1) {
  4060. GLTFLoader._ExtensionNames.splice(index, 1);
  4061. }
  4062. return true;
  4063. };
  4064. Object.defineProperty(GLTFLoader.prototype, "state", {
  4065. /**
  4066. * Gets the loader state.
  4067. */
  4068. get: function () {
  4069. return this._state;
  4070. },
  4071. enumerable: true,
  4072. configurable: true
  4073. });
  4074. /** @hidden */
  4075. GLTFLoader.prototype.dispose = function () {
  4076. if (this._disposed) {
  4077. return;
  4078. }
  4079. this._disposed = true;
  4080. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  4081. var request = _a[_i];
  4082. request.abort();
  4083. }
  4084. this._requests.length = 0;
  4085. delete this.gltf;
  4086. delete this.babylonScene;
  4087. this._completePromises.length = 0;
  4088. for (var name_1 in this._extensions) {
  4089. var extension = this._extensions[name_1];
  4090. if (extension.dispose) {
  4091. this._extensions[name_1].dispose();
  4092. }
  4093. }
  4094. this._extensions = {};
  4095. delete this._rootBabylonMesh;
  4096. delete this._progressCallback;
  4097. this._parent._clear();
  4098. };
  4099. /** @hidden */
  4100. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  4101. var _this = this;
  4102. return Promise.resolve().then(function () {
  4103. _this.babylonScene = scene;
  4104. _this._rootUrl = rootUrl;
  4105. _this._fileName = fileName || "scene";
  4106. _this._progressCallback = onProgress;
  4107. _this._loadData(data);
  4108. var nodes = null;
  4109. if (meshesNames) {
  4110. var nodeMap_1 = {};
  4111. if (_this.gltf.nodes) {
  4112. for (var _i = 0, _a = _this.gltf.nodes; _i < _a.length; _i++) {
  4113. var node = _a[_i];
  4114. if (node.name) {
  4115. nodeMap_1[node.name] = node.index;
  4116. }
  4117. }
  4118. }
  4119. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  4120. nodes = names.map(function (name) {
  4121. var node = nodeMap_1[name];
  4122. if (node === undefined) {
  4123. throw new Error("Failed to find node '" + name + "'");
  4124. }
  4125. return node;
  4126. });
  4127. }
  4128. return _this._loadAsync(nodes, function () {
  4129. return {
  4130. meshes: _this._getMeshes(),
  4131. particleSystems: [],
  4132. skeletons: _this._getSkeletons(),
  4133. animationGroups: _this._getAnimationGroups()
  4134. };
  4135. });
  4136. });
  4137. };
  4138. /** @hidden */
  4139. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  4140. var _this = this;
  4141. return Promise.resolve().then(function () {
  4142. _this.babylonScene = scene;
  4143. _this._rootUrl = rootUrl;
  4144. _this._fileName = fileName || "scene";
  4145. _this._progressCallback = onProgress;
  4146. _this._loadData(data);
  4147. return _this._loadAsync(null, function () { return undefined; });
  4148. });
  4149. };
  4150. GLTFLoader.prototype._loadAsync = function (nodes, resultFunc) {
  4151. var _this = this;
  4152. return Promise.resolve().then(function () {
  4153. _this._uniqueRootUrl = (_this._rootUrl.indexOf("file:") === -1 && _this._fileName) ? _this._rootUrl : "" + _this._rootUrl + Date.now() + "/";
  4154. _this._loadExtensions();
  4155. _this._checkExtensions();
  4156. var loadingToReadyCounterName = BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.LOADING] + " => " + BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.READY];
  4157. var loadingToCompleteCounterName = BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.LOADING] + " => " + BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.COMPLETE];
  4158. _this._parent._startPerformanceCounter(loadingToReadyCounterName);
  4159. _this._parent._startPerformanceCounter(loadingToCompleteCounterName);
  4160. _this._setState(BABYLON.GLTFLoaderState.LOADING);
  4161. _this._extensionsOnLoading();
  4162. var promises = new Array();
  4163. if (nodes) {
  4164. promises.push(_this.loadSceneAsync("#/nodes", { nodes: nodes, index: -1 }));
  4165. }
  4166. else {
  4167. var scene = ArrayItem.Get("#/scene", _this.gltf.scenes, _this.gltf.scene || 0);
  4168. promises.push(_this.loadSceneAsync("#/scenes/" + scene.index, scene));
  4169. }
  4170. if (_this._parent.compileMaterials) {
  4171. promises.push(_this._compileMaterialsAsync());
  4172. }
  4173. if (_this._parent.compileShadowGenerators) {
  4174. promises.push(_this._compileShadowGeneratorsAsync());
  4175. }
  4176. var resultPromise = Promise.all(promises).then(function () {
  4177. _this._setState(BABYLON.GLTFLoaderState.READY);
  4178. _this._extensionsOnReady();
  4179. _this._startAnimations();
  4180. return resultFunc();
  4181. });
  4182. resultPromise.then(function () {
  4183. _this._parent._endPerformanceCounter(loadingToReadyCounterName);
  4184. BABYLON.Tools.SetImmediate(function () {
  4185. if (!_this._disposed) {
  4186. Promise.all(_this._completePromises).then(function () {
  4187. _this._parent._endPerformanceCounter(loadingToCompleteCounterName);
  4188. _this._setState(BABYLON.GLTFLoaderState.COMPLETE);
  4189. _this._parent.onCompleteObservable.notifyObservers(undefined);
  4190. _this._parent.onCompleteObservable.clear();
  4191. _this.dispose();
  4192. }, function (error) {
  4193. _this._parent.onErrorObservable.notifyObservers(error);
  4194. _this._parent.onErrorObservable.clear();
  4195. _this.dispose();
  4196. });
  4197. }
  4198. });
  4199. });
  4200. return resultPromise;
  4201. }, function (error) {
  4202. if (!_this._disposed) {
  4203. _this._parent.onErrorObservable.notifyObservers(error);
  4204. _this._parent.onErrorObservable.clear();
  4205. _this.dispose();
  4206. }
  4207. throw error;
  4208. });
  4209. };
  4210. GLTFLoader.prototype._loadData = function (data) {
  4211. this.gltf = data.json;
  4212. this._setupData();
  4213. if (data.bin) {
  4214. var buffers = this.gltf.buffers;
  4215. if (buffers && buffers[0] && !buffers[0].uri) {
  4216. var binaryBuffer = buffers[0];
  4217. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  4218. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  4219. }
  4220. binaryBuffer._data = Promise.resolve(data.bin);
  4221. }
  4222. else {
  4223. BABYLON.Tools.Warn("Unexpected BIN chunk");
  4224. }
  4225. }
  4226. };
  4227. GLTFLoader.prototype._setupData = function () {
  4228. ArrayItem.Assign(this.gltf.accessors);
  4229. ArrayItem.Assign(this.gltf.animations);
  4230. ArrayItem.Assign(this.gltf.buffers);
  4231. ArrayItem.Assign(this.gltf.bufferViews);
  4232. ArrayItem.Assign(this.gltf.cameras);
  4233. ArrayItem.Assign(this.gltf.images);
  4234. ArrayItem.Assign(this.gltf.materials);
  4235. ArrayItem.Assign(this.gltf.meshes);
  4236. ArrayItem.Assign(this.gltf.nodes);
  4237. ArrayItem.Assign(this.gltf.samplers);
  4238. ArrayItem.Assign(this.gltf.scenes);
  4239. ArrayItem.Assign(this.gltf.skins);
  4240. ArrayItem.Assign(this.gltf.textures);
  4241. if (this.gltf.nodes) {
  4242. var nodeParents = {};
  4243. for (var _i = 0, _a = this.gltf.nodes; _i < _a.length; _i++) {
  4244. var node = _a[_i];
  4245. if (node.children) {
  4246. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  4247. var index = _c[_b];
  4248. nodeParents[index] = node.index;
  4249. }
  4250. }
  4251. }
  4252. var rootNode = this._createRootNode();
  4253. for (var _d = 0, _e = this.gltf.nodes; _d < _e.length; _d++) {
  4254. var node = _e[_d];
  4255. var parentIndex = nodeParents[node.index];
  4256. node.parent = parentIndex === undefined ? rootNode : this.gltf.nodes[parentIndex];
  4257. }
  4258. }
  4259. };
  4260. GLTFLoader.prototype._loadExtensions = function () {
  4261. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  4262. var name_2 = _a[_i];
  4263. var extension = GLTFLoader._ExtensionFactories[name_2](this);
  4264. this._extensions[name_2] = extension;
  4265. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  4266. }
  4267. this._parent.onExtensionLoadedObservable.clear();
  4268. };
  4269. GLTFLoader.prototype._checkExtensions = function () {
  4270. if (this.gltf.extensionsRequired) {
  4271. for (var _i = 0, _a = this.gltf.extensionsRequired; _i < _a.length; _i++) {
  4272. var name_3 = _a[_i];
  4273. var extension = this._extensions[name_3];
  4274. if (!extension || !extension.enabled) {
  4275. throw new Error("Require extension " + name_3 + " is not available");
  4276. }
  4277. }
  4278. }
  4279. };
  4280. GLTFLoader.prototype._setState = function (state) {
  4281. this._state = state;
  4282. this.log(BABYLON.GLTFLoaderState[this._state]);
  4283. };
  4284. GLTFLoader.prototype._createRootNode = function () {
  4285. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this.babylonScene);
  4286. var rootNode = {
  4287. _babylonMesh: this._rootBabylonMesh,
  4288. index: -1
  4289. };
  4290. switch (this._parent.coordinateSystemMode) {
  4291. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  4292. if (!this.babylonScene.useRightHandedSystem) {
  4293. rootNode.rotation = [0, 1, 0, 0];
  4294. rootNode.scale = [1, 1, -1];
  4295. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  4296. }
  4297. break;
  4298. }
  4299. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  4300. this.babylonScene.useRightHandedSystem = true;
  4301. break;
  4302. }
  4303. default: {
  4304. throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  4305. }
  4306. }
  4307. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  4308. return rootNode;
  4309. };
  4310. /**
  4311. * Loads a glTF scene.
  4312. * @param context The context when loading the asset
  4313. * @param scene The glTF scene property
  4314. * @returns A promise that resolves when the load is complete
  4315. */
  4316. GLTFLoader.prototype.loadSceneAsync = function (context, scene) {
  4317. var _this = this;
  4318. var extensionPromise = this._extensionsLoadSceneAsync(context, scene);
  4319. if (extensionPromise) {
  4320. return extensionPromise;
  4321. }
  4322. var promises = new Array();
  4323. this.logOpen(context + " " + (scene.name || ""));
  4324. if (scene.nodes) {
  4325. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  4326. var index = _a[_i];
  4327. var node = ArrayItem.Get(context + "/nodes/" + index, this.gltf.nodes, index);
  4328. promises.push(this.loadNodeAsync("#/nodes/" + node.index, node, function (babylonMesh) {
  4329. babylonMesh.parent = _this._rootBabylonMesh;
  4330. }));
  4331. }
  4332. }
  4333. promises.push(this._loadAnimationsAsync());
  4334. this.logClose();
  4335. return Promise.all(promises).then(function () { });
  4336. };
  4337. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  4338. if (node._primitiveBabylonMeshes) {
  4339. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  4340. var babylonMesh = _a[_i];
  4341. callback(babylonMesh);
  4342. }
  4343. }
  4344. else {
  4345. callback(node._babylonMesh);
  4346. }
  4347. };
  4348. GLTFLoader.prototype._getMeshes = function () {
  4349. var meshes = new Array();
  4350. // Root mesh is always first.
  4351. meshes.push(this._rootBabylonMesh);
  4352. var nodes = this.gltf.nodes;
  4353. if (nodes) {
  4354. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  4355. var node = nodes_1[_i];
  4356. if (node._babylonMesh) {
  4357. meshes.push(node._babylonMesh);
  4358. }
  4359. if (node._primitiveBabylonMeshes) {
  4360. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  4361. var babylonMesh = _b[_a];
  4362. meshes.push(babylonMesh);
  4363. }
  4364. }
  4365. }
  4366. }
  4367. return meshes;
  4368. };
  4369. GLTFLoader.prototype._getSkeletons = function () {
  4370. var skeletons = new Array();
  4371. var skins = this.gltf.skins;
  4372. if (skins) {
  4373. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  4374. var skin = skins_1[_i];
  4375. if (skin._babylonSkeleton) {
  4376. skeletons.push(skin._babylonSkeleton);
  4377. }
  4378. }
  4379. }
  4380. return skeletons;
  4381. };
  4382. GLTFLoader.prototype._getAnimationGroups = function () {
  4383. var animationGroups = new Array();
  4384. var animations = this.gltf.animations;
  4385. if (animations) {
  4386. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  4387. var animation = animations_1[_i];
  4388. if (animation._babylonAnimationGroup) {
  4389. animationGroups.push(animation._babylonAnimationGroup);
  4390. }
  4391. }
  4392. }
  4393. return animationGroups;
  4394. };
  4395. GLTFLoader.prototype._startAnimations = function () {
  4396. switch (this._parent.animationStartMode) {
  4397. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  4398. // do nothing
  4399. break;
  4400. }
  4401. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  4402. var babylonAnimationGroups = this._getAnimationGroups();
  4403. if (babylonAnimationGroups.length !== 0) {
  4404. babylonAnimationGroups[0].start(true);
  4405. }
  4406. break;
  4407. }
  4408. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  4409. var babylonAnimationGroups = this._getAnimationGroups();
  4410. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  4411. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  4412. babylonAnimationGroup.start(true);
  4413. }
  4414. break;
  4415. }
  4416. default: {
  4417. BABYLON.Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
  4418. return;
  4419. }
  4420. }
  4421. };
  4422. /**
  4423. * Loads a glTF node.
  4424. * @param context The context when loading the asset
  4425. * @param node The glTF node property
  4426. * @param assign A function called synchronously after parsing the glTF properties
  4427. * @returns A promise that resolves with the loaded Babylon mesh when the load is complete
  4428. */
  4429. GLTFLoader.prototype.loadNodeAsync = function (context, node, assign) {
  4430. var _this = this;
  4431. if (assign === void 0) { assign = function () { }; }
  4432. var extensionPromise = this._extensionsLoadNodeAsync(context, node, assign);
  4433. if (extensionPromise) {
  4434. return extensionPromise;
  4435. }
  4436. if (node._babylonMesh) {
  4437. throw new Error(context + ": Invalid recursive node hierarchy");
  4438. }
  4439. var promises = new Array();
  4440. this.logOpen(context + " " + (node.name || ""));
  4441. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node.index, this.babylonScene);
  4442. node._babylonMesh = babylonMesh;
  4443. babylonMesh.setEnabled(false);
  4444. GLTFLoader._LoadTransform(node, babylonMesh);
  4445. if (node.mesh != undefined) {
  4446. var mesh = ArrayItem.Get(context + "/mesh", this.gltf.meshes, node.mesh);
  4447. promises.push(this._loadMeshAsync("#/meshes/" + mesh.index, node, mesh, babylonMesh));
  4448. }
  4449. if (node.camera != undefined) {
  4450. var camera = ArrayItem.Get(context + "/camera", this.gltf.cameras, node.camera);
  4451. promises.push(this.loadCameraAsync("#/cameras/" + camera.index, camera, function (babylonCamera) {
  4452. babylonCamera.parent = babylonMesh;
  4453. }));
  4454. }
  4455. if (node.children) {
  4456. var _loop_1 = function (index) {
  4457. var childNode = ArrayItem.Get(context + "/children/" + index, this_1.gltf.nodes, index);
  4458. promises.push(this_1.loadNodeAsync("#/nodes/" + node.index, childNode, function (childBabylonMesh) {
  4459. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  4460. if (childNode.skin != undefined) {
  4461. childBabylonMesh.parent = _this._rootBabylonMesh;
  4462. return;
  4463. }
  4464. childBabylonMesh.parent = babylonMesh;
  4465. }));
  4466. };
  4467. var this_1 = this;
  4468. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  4469. var index = _a[_i];
  4470. _loop_1(index);
  4471. }
  4472. }
  4473. assign(babylonMesh);
  4474. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  4475. this.logClose();
  4476. return Promise.all(promises).then(function () {
  4477. babylonMesh.setEnabled(true);
  4478. return babylonMesh;
  4479. });
  4480. };
  4481. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  4482. var _this = this;
  4483. var promises = new Array();
  4484. this.logOpen(context + " " + (mesh.name || ""));
  4485. var primitives = mesh.primitives;
  4486. if (!primitives || primitives.length === 0) {
  4487. throw new Error(context + ": Primitives are missing");
  4488. }
  4489. ArrayItem.Assign(primitives);
  4490. if (primitives.length === 1) {
  4491. var primitive = primitives[0];
  4492. promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, node, mesh, primitive, babylonMesh));
  4493. }
  4494. else {
  4495. node._primitiveBabylonMeshes = [];
  4496. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  4497. var primitive = primitives_1[_i];
  4498. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive.index, this.babylonScene, babylonMesh);
  4499. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  4500. promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, node, mesh, primitive, primitiveBabylonMesh));
  4501. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  4502. }
  4503. }
  4504. if (node.skin != undefined) {
  4505. var skin = ArrayItem.Get(context + "/skin", this.gltf.skins, node.skin);
  4506. promises.push(this._loadSkinAsync("#/skins/" + skin.index, node, skin));
  4507. }
  4508. this.logClose();
  4509. return Promise.all(promises).then(function () {
  4510. _this._forEachPrimitive(node, function (babylonMesh) {
  4511. babylonMesh._refreshBoundingInfo(true);
  4512. });
  4513. });
  4514. };
  4515. GLTFLoader.prototype._loadMeshPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  4516. var _this = this;
  4517. var promises = new Array();
  4518. this.logOpen("" + context);
  4519. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  4520. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  4521. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  4522. babylonGeometry.applyToMesh(babylonMesh);
  4523. });
  4524. }));
  4525. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  4526. if (primitive.material == undefined) {
  4527. var babylonMaterial = this._defaultBabylonMaterialData[babylonDrawMode];
  4528. if (!babylonMaterial) {
  4529. babylonMaterial = this._createDefaultMaterial("__gltf_default", babylonDrawMode);
  4530. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  4531. this._defaultBabylonMaterialData[babylonDrawMode] = babylonMaterial;
  4532. }
  4533. babylonMesh.material = babylonMaterial;
  4534. }
  4535. else {
  4536. var material = ArrayItem.Get(context + "/material", this.gltf.materials, primitive.material);
  4537. promises.push(this._loadMaterialAsync("#/materials/" + material.index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  4538. babylonMesh.material = babylonMaterial;
  4539. }));
  4540. }
  4541. this.logClose();
  4542. return Promise.all(promises).then(function () { });
  4543. };
  4544. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  4545. var _this = this;
  4546. var extensionPromise = this._extensionsLoadVertexDataAsync(context, primitive, babylonMesh);
  4547. if (extensionPromise) {
  4548. return extensionPromise;
  4549. }
  4550. var attributes = primitive.attributes;
  4551. if (!attributes) {
  4552. throw new Error(context + ": Attributes are missing");
  4553. }
  4554. var promises = new Array();
  4555. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this.babylonScene);
  4556. if (primitive.indices == undefined) {
  4557. babylonMesh.isUnIndexed = true;
  4558. }
  4559. else {
  4560. var accessor = ArrayItem.Get(context + "/indices", this.gltf.accessors, primitive.indices);
  4561. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  4562. babylonGeometry.setIndices(data);
  4563. }));
  4564. }
  4565. var loadAttribute = function (attribute, kind, callback) {
  4566. if (attributes[attribute] == undefined) {
  4567. return;
  4568. }
  4569. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  4570. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  4571. babylonMesh._delayInfo.push(kind);
  4572. }
  4573. var accessor = ArrayItem.Get(context + "/attributes/" + attribute, _this.gltf.accessors, attributes[attribute]);
  4574. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor.index, accessor, kind).then(function (babylonVertexBuffer) {
  4575. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  4576. }));
  4577. if (callback) {
  4578. callback(accessor);
  4579. }
  4580. };
  4581. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  4582. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  4583. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  4584. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  4585. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  4586. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  4587. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  4588. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  4589. if (accessor.type === "VEC4" /* VEC4 */) {
  4590. babylonMesh.hasVertexAlpha = true;
  4591. }
  4592. });
  4593. return Promise.all(promises).then(function () {
  4594. return babylonGeometry;
  4595. });
  4596. };
  4597. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  4598. if (!primitive.targets) {
  4599. return;
  4600. }
  4601. if (node._numMorphTargets == undefined) {
  4602. node._numMorphTargets = primitive.targets.length;
  4603. }
  4604. else if (primitive.targets.length !== node._numMorphTargets) {
  4605. throw new Error(context + ": Primitives do not have the same number of targets");
  4606. }
  4607. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  4608. for (var index = 0; index < primitive.targets.length; index++) {
  4609. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  4610. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  4611. // TODO: tell the target whether it has positions, normals, tangents
  4612. }
  4613. };
  4614. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  4615. if (!primitive.targets) {
  4616. return Promise.resolve();
  4617. }
  4618. var promises = new Array();
  4619. var morphTargetManager = babylonMesh.morphTargetManager;
  4620. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  4621. var babylonMorphTarget = morphTargetManager.getTarget(index);
  4622. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  4623. }
  4624. return Promise.all(promises).then(function () { });
  4625. };
  4626. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  4627. var _this = this;
  4628. var promises = new Array();
  4629. var loadAttribute = function (attribute, kind, setData) {
  4630. if (attributes[attribute] == undefined) {
  4631. return;
  4632. }
  4633. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  4634. if (!babylonVertexBuffer) {
  4635. return;
  4636. }
  4637. var accessor = ArrayItem.Get(context + "/" + attribute, _this.gltf.accessors, attributes[attribute]);
  4638. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  4639. setData(babylonVertexBuffer, data);
  4640. }));
  4641. };
  4642. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  4643. babylonVertexBuffer.forEach(data.length, function (value, index) {
  4644. data[index] += value;
  4645. });
  4646. babylonMorphTarget.setPositions(data);
  4647. });
  4648. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  4649. babylonVertexBuffer.forEach(data.length, function (value, index) {
  4650. data[index] += value;
  4651. });
  4652. babylonMorphTarget.setNormals(data);
  4653. });
  4654. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  4655. var dataIndex = 0;
  4656. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  4657. // Tangent data for morph targets is stored as xyz delta.
  4658. // The vertexData.tangent is stored as xyzw.
  4659. // So we need to skip every fourth vertexData.tangent.
  4660. if (((index + 1) % 4) !== 0) {
  4661. data[dataIndex++] += value;
  4662. }
  4663. });
  4664. babylonMorphTarget.setTangents(data);
  4665. });
  4666. return Promise.all(promises).then(function () { });
  4667. };
  4668. GLTFLoader._LoadTransform = function (node, babylonNode) {
  4669. var position = BABYLON.Vector3.Zero();
  4670. var rotation = BABYLON.Quaternion.Identity();
  4671. var scaling = BABYLON.Vector3.One();
  4672. if (node.matrix) {
  4673. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  4674. matrix.decompose(scaling, rotation, position);
  4675. }
  4676. else {
  4677. if (node.translation) {
  4678. position = BABYLON.Vector3.FromArray(node.translation);
  4679. }
  4680. if (node.rotation) {
  4681. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  4682. }
  4683. if (node.scale) {
  4684. scaling = BABYLON.Vector3.FromArray(node.scale);
  4685. }
  4686. }
  4687. babylonNode.position = position;
  4688. babylonNode.rotationQuaternion = rotation;
  4689. babylonNode.scaling = scaling;
  4690. };
  4691. GLTFLoader.prototype._loadSkinAsync = function (context, node, skin) {
  4692. var _this = this;
  4693. var assignSkeleton = function (skeleton) {
  4694. _this._forEachPrimitive(node, function (babylonMesh) {
  4695. babylonMesh.skeleton = skeleton;
  4696. });
  4697. // Ignore the TRS of skinned nodes.
  4698. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  4699. node._babylonMesh.position = BABYLON.Vector3.Zero();
  4700. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  4701. node._babylonMesh.scaling = BABYLON.Vector3.One();
  4702. };
  4703. if (skin._promise) {
  4704. return skin._promise.then(function () {
  4705. assignSkeleton(skin._babylonSkeleton);
  4706. });
  4707. }
  4708. var skeletonId = "skeleton" + skin.index;
  4709. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this.babylonScene);
  4710. skin._babylonSkeleton = babylonSkeleton;
  4711. this._loadBones(context, skin);
  4712. assignSkeleton(babylonSkeleton);
  4713. return (skin._promise = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  4714. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  4715. }));
  4716. };
  4717. GLTFLoader.prototype._loadBones = function (context, skin) {
  4718. var babylonBones = {};
  4719. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  4720. var index = _a[_i];
  4721. var node = ArrayItem.Get(context + "/joints/" + index, this.gltf.nodes, index);
  4722. this._loadBone(node, skin, babylonBones);
  4723. }
  4724. };
  4725. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  4726. var babylonBone = babylonBones[node.index];
  4727. if (babylonBone) {
  4728. return babylonBone;
  4729. }
  4730. var babylonParentBone = null;
  4731. if (node.parent && node.parent._babylonMesh !== this._rootBabylonMesh) {
  4732. babylonParentBone = this._loadBone(node.parent, skin, babylonBones);
  4733. }
  4734. var boneIndex = skin.joints.indexOf(node.index);
  4735. babylonBone = new BABYLON.Bone(node.name || "joint" + node.index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  4736. babylonBones[node.index] = babylonBone;
  4737. node._babylonBones = node._babylonBones || [];
  4738. node._babylonBones.push(babylonBone);
  4739. return babylonBone;
  4740. };
  4741. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  4742. if (skin.inverseBindMatrices == undefined) {
  4743. return Promise.resolve(null);
  4744. }
  4745. var accessor = ArrayItem.Get(context + "/inverseBindMatrices", this.gltf.accessors, skin.inverseBindMatrices);
  4746. return this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor);
  4747. };
  4748. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  4749. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  4750. var babylonBone = _a[_i];
  4751. var baseMatrix = BABYLON.Matrix.Identity();
  4752. var boneIndex = babylonBone._index;
  4753. if (inverseBindMatricesData && boneIndex !== -1) {
  4754. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  4755. baseMatrix.invertToRef(baseMatrix);
  4756. }
  4757. var babylonParentBone = babylonBone.getParent();
  4758. if (babylonParentBone) {
  4759. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  4760. }
  4761. babylonBone.updateMatrix(baseMatrix, false, false);
  4762. babylonBone._updateDifferenceMatrix(undefined, false);
  4763. }
  4764. };
  4765. GLTFLoader.prototype._getNodeMatrix = function (node) {
  4766. return node.matrix ?
  4767. BABYLON.Matrix.FromArray(node.matrix) :
  4768. 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());
  4769. };
  4770. /**
  4771. * Loads a glTF camera.
  4772. * @param context The context when loading the asset
  4773. * @param camera The glTF camera property
  4774. * @param assign A function called synchronously after parsing the glTF properties
  4775. * @returns A promise that resolves with the loaded Babylon camera when the load is complete
  4776. */
  4777. GLTFLoader.prototype.loadCameraAsync = function (context, camera, assign) {
  4778. if (assign === void 0) { assign = function () { }; }
  4779. var extensionPromise = this._extensionsLoadCameraAsync(context, camera, assign);
  4780. if (extensionPromise) {
  4781. return extensionPromise;
  4782. }
  4783. var promises = new Array();
  4784. this.logOpen(context + " " + (camera.name || ""));
  4785. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera.index, BABYLON.Vector3.Zero(), this.babylonScene, false);
  4786. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  4787. switch (camera.type) {
  4788. case "perspective" /* PERSPECTIVE */: {
  4789. var perspective = camera.perspective;
  4790. if (!perspective) {
  4791. throw new Error(context + ": Camera perspective properties are missing");
  4792. }
  4793. babylonCamera.fov = perspective.yfov;
  4794. babylonCamera.minZ = perspective.znear;
  4795. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  4796. break;
  4797. }
  4798. case "orthographic" /* ORTHOGRAPHIC */: {
  4799. if (!camera.orthographic) {
  4800. throw new Error(context + ": Camera orthographic properties are missing");
  4801. }
  4802. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  4803. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  4804. babylonCamera.orthoRight = camera.orthographic.xmag;
  4805. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  4806. babylonCamera.orthoTop = camera.orthographic.ymag;
  4807. babylonCamera.minZ = camera.orthographic.znear;
  4808. babylonCamera.maxZ = camera.orthographic.zfar;
  4809. break;
  4810. }
  4811. default: {
  4812. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  4813. }
  4814. }
  4815. assign(babylonCamera);
  4816. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  4817. return Promise.all(promises).then(function () {
  4818. return babylonCamera;
  4819. });
  4820. };
  4821. GLTFLoader.prototype._loadAnimationsAsync = function () {
  4822. var animations = this.gltf.animations;
  4823. if (!animations) {
  4824. return Promise.resolve();
  4825. }
  4826. var promises = new Array();
  4827. for (var index = 0; index < animations.length; index++) {
  4828. var animation = animations[index];
  4829. promises.push(this.loadAnimationAsync("#/animations/" + animation.index, animation));
  4830. }
  4831. return Promise.all(promises).then(function () { });
  4832. };
  4833. /**
  4834. * Loads a glTF animation.
  4835. * @param context The context when loading the asset
  4836. * @param animation The glTF animation property
  4837. * @returns A promise that resolves with the loaded Babylon animation group when the load is complete
  4838. */
  4839. GLTFLoader.prototype.loadAnimationAsync = function (context, animation) {
  4840. var promise = this._extensionsLoadAnimationAsync(context, animation);
  4841. if (promise) {
  4842. return promise;
  4843. }
  4844. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation.index, this.babylonScene);
  4845. animation._babylonAnimationGroup = babylonAnimationGroup;
  4846. var promises = new Array();
  4847. ArrayItem.Assign(animation.channels);
  4848. ArrayItem.Assign(animation.samplers);
  4849. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  4850. var channel = _a[_i];
  4851. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel.index, context, animation, channel, babylonAnimationGroup));
  4852. }
  4853. return Promise.all(promises).then(function () {
  4854. babylonAnimationGroup.normalize(0);
  4855. return babylonAnimationGroup;
  4856. });
  4857. };
  4858. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  4859. var _this = this;
  4860. var targetNode = ArrayItem.Get(context + "/target/node", this.gltf.nodes, channel.target.node);
  4861. // Ignore animations that have no animation targets.
  4862. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  4863. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  4864. return Promise.resolve();
  4865. }
  4866. // Ignore animations targeting TRS of skinned nodes.
  4867. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  4868. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  4869. return Promise.resolve();
  4870. }
  4871. var sampler = ArrayItem.Get(context + "/sampler", animation.samplers, channel.sampler);
  4872. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  4873. var targetPath;
  4874. var animationType;
  4875. switch (channel.target.path) {
  4876. case "translation" /* TRANSLATION */: {
  4877. targetPath = "position";
  4878. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  4879. break;
  4880. }
  4881. case "rotation" /* ROTATION */: {
  4882. targetPath = "rotationQuaternion";
  4883. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  4884. break;
  4885. }
  4886. case "scale" /* SCALE */: {
  4887. targetPath = "scaling";
  4888. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  4889. break;
  4890. }
  4891. case "weights" /* WEIGHTS */: {
  4892. targetPath = "influence";
  4893. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  4894. break;
  4895. }
  4896. default: {
  4897. throw new Error(context + "/target/path: Invalid value (" + channel.target.path + ")");
  4898. }
  4899. }
  4900. var outputBufferOffset = 0;
  4901. var getNextOutputValue;
  4902. switch (targetPath) {
  4903. case "position": {
  4904. getNextOutputValue = function () {
  4905. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  4906. outputBufferOffset += 3;
  4907. return value;
  4908. };
  4909. break;
  4910. }
  4911. case "rotationQuaternion": {
  4912. getNextOutputValue = function () {
  4913. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  4914. outputBufferOffset += 4;
  4915. return value;
  4916. };
  4917. break;
  4918. }
  4919. case "scaling": {
  4920. getNextOutputValue = function () {
  4921. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  4922. outputBufferOffset += 3;
  4923. return value;
  4924. };
  4925. break;
  4926. }
  4927. case "influence": {
  4928. getNextOutputValue = function () {
  4929. var value = new Array(targetNode._numMorphTargets);
  4930. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  4931. value[i] = data.output[outputBufferOffset++];
  4932. }
  4933. return value;
  4934. };
  4935. break;
  4936. }
  4937. }
  4938. var getNextKey;
  4939. switch (data.interpolation) {
  4940. case "STEP" /* STEP */: {
  4941. getNextKey = function (frameIndex) { return ({
  4942. frame: data.input[frameIndex],
  4943. value: getNextOutputValue(),
  4944. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  4945. }); };
  4946. break;
  4947. }
  4948. case "LINEAR" /* LINEAR */: {
  4949. getNextKey = function (frameIndex) { return ({
  4950. frame: data.input[frameIndex],
  4951. value: getNextOutputValue()
  4952. }); };
  4953. break;
  4954. }
  4955. case "CUBICSPLINE" /* CUBICSPLINE */: {
  4956. getNextKey = function (frameIndex) { return ({
  4957. frame: data.input[frameIndex],
  4958. inTangent: getNextOutputValue(),
  4959. value: getNextOutputValue(),
  4960. outTangent: getNextOutputValue()
  4961. }); };
  4962. break;
  4963. }
  4964. }
  4965. var keys = new Array(data.input.length);
  4966. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  4967. keys[frameIndex] = getNextKey(frameIndex);
  4968. }
  4969. if (targetPath === "influence") {
  4970. var _loop_2 = function (targetIndex) {
  4971. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  4972. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  4973. babylonAnimation.setKeys(keys.map(function (key) { return ({
  4974. frame: key.frame,
  4975. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  4976. value: key.value[targetIndex],
  4977. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  4978. }); }));
  4979. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  4980. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  4981. var babylonAnimationClone = babylonAnimation.clone();
  4982. morphTarget.animations.push(babylonAnimationClone);
  4983. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  4984. });
  4985. };
  4986. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  4987. _loop_2(targetIndex);
  4988. }
  4989. }
  4990. else {
  4991. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  4992. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  4993. babylonAnimation.setKeys(keys);
  4994. if (targetNode._babylonBones) {
  4995. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  4996. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  4997. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  4998. babylonAnimationTarget.animations.push(babylonAnimation);
  4999. }
  5000. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  5001. }
  5002. else {
  5003. targetNode._babylonMesh.animations.push(babylonAnimation);
  5004. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  5005. }
  5006. }
  5007. });
  5008. };
  5009. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  5010. if (sampler._data) {
  5011. return sampler._data;
  5012. }
  5013. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  5014. switch (interpolation) {
  5015. case "STEP" /* STEP */:
  5016. case "LINEAR" /* LINEAR */:
  5017. case "CUBICSPLINE" /* CUBICSPLINE */: {
  5018. break;
  5019. }
  5020. default: {
  5021. throw new Error(context + "/interpolation: Invalid value (" + sampler.interpolation + ")");
  5022. }
  5023. }
  5024. var inputAccessor = ArrayItem.Get(context + "/input", this.gltf.accessors, sampler.input);
  5025. var outputAccessor = ArrayItem.Get(context + "/output", this.gltf.accessors, sampler.output);
  5026. sampler._data = Promise.all([
  5027. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor),
  5028. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor)
  5029. ]).then(function (_a) {
  5030. var inputData = _a[0], outputData = _a[1];
  5031. return {
  5032. input: inputData,
  5033. interpolation: interpolation,
  5034. output: outputData,
  5035. };
  5036. });
  5037. return sampler._data;
  5038. };
  5039. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  5040. if (buffer._data) {
  5041. return buffer._data;
  5042. }
  5043. if (!buffer.uri) {
  5044. throw new Error(context + "/uri: Value is missing");
  5045. }
  5046. buffer._data = this.loadUriAsync(context + "/uri", buffer.uri);
  5047. return buffer._data;
  5048. };
  5049. /**
  5050. * Loads a glTF buffer view.
  5051. * @param context The context when loading the asset
  5052. * @param bufferView The glTF buffer view property
  5053. * @returns A promise that resolves with the loaded data when the load is complete
  5054. */
  5055. GLTFLoader.prototype.loadBufferViewAsync = function (context, bufferView) {
  5056. if (bufferView._data) {
  5057. return bufferView._data;
  5058. }
  5059. var buffer = ArrayItem.Get(context + "/buffer", this.gltf.buffers, bufferView.buffer);
  5060. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer.index, buffer).then(function (data) {
  5061. try {
  5062. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  5063. }
  5064. catch (e) {
  5065. throw new Error(context + ": " + e.message);
  5066. }
  5067. });
  5068. return bufferView._data;
  5069. };
  5070. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  5071. if (accessor.type !== "SCALAR" /* SCALAR */) {
  5072. throw new Error(context + "/type: Invalid value " + accessor.type);
  5073. }
  5074. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  5075. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  5076. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  5077. throw new Error(context + "/componentType: Invalid value " + accessor.componentType);
  5078. }
  5079. if (accessor._data) {
  5080. return accessor._data;
  5081. }
  5082. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  5083. accessor._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  5084. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  5085. });
  5086. return accessor._data;
  5087. };
  5088. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  5089. // TODO: support normalized and stride
  5090. var _this = this;
  5091. if (accessor.componentType !== 5126 /* FLOAT */) {
  5092. throw new Error("Invalid component type " + accessor.componentType);
  5093. }
  5094. if (accessor._data) {
  5095. return accessor._data;
  5096. }
  5097. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  5098. var length = numComponents * accessor.count;
  5099. if (accessor.bufferView == undefined) {
  5100. accessor._data = Promise.resolve(new Float32Array(length));
  5101. }
  5102. else {
  5103. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  5104. accessor._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  5105. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  5106. });
  5107. }
  5108. if (accessor.sparse) {
  5109. var sparse_1 = accessor.sparse;
  5110. accessor._data = accessor._data.then(function (data) {
  5111. var indicesBufferView = ArrayItem.Get(context + "/sparse/indices/bufferView", _this.gltf.bufferViews, sparse_1.indices.bufferView);
  5112. var valuesBufferView = ArrayItem.Get(context + "/sparse/values/bufferView", _this.gltf.bufferViews, sparse_1.values.bufferView);
  5113. return Promise.all([
  5114. _this.loadBufferViewAsync("#/bufferViews/" + indicesBufferView.index, indicesBufferView),
  5115. _this.loadBufferViewAsync("#/bufferViews/" + valuesBufferView.index, valuesBufferView)
  5116. ]).then(function (_a) {
  5117. var indicesData = _a[0], valuesData = _a[1];
  5118. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  5119. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  5120. var valuesIndex = 0;
  5121. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  5122. var dataIndex = indices[indicesIndex] * numComponents;
  5123. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  5124. data[dataIndex++] = values[valuesIndex++];
  5125. }
  5126. }
  5127. return data;
  5128. });
  5129. });
  5130. }
  5131. return accessor._data;
  5132. };
  5133. GLTFLoader.prototype._loadVertexBufferViewAsync = function (bufferView, kind) {
  5134. var _this = this;
  5135. if (bufferView._babylonBuffer) {
  5136. return bufferView._babylonBuffer;
  5137. }
  5138. bufferView._babylonBuffer = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  5139. return new BABYLON.Buffer(_this.babylonScene.getEngine(), data, false);
  5140. });
  5141. return bufferView._babylonBuffer;
  5142. };
  5143. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  5144. var _this = this;
  5145. if (accessor._babylonVertexBuffer) {
  5146. return accessor._babylonVertexBuffer;
  5147. }
  5148. if (accessor.sparse) {
  5149. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  5150. return new BABYLON.VertexBuffer(_this.babylonScene.getEngine(), data, kind, false);
  5151. });
  5152. }
  5153. // HACK: If byte offset is not a multiple of component type byte length then load as a float array instead of using Babylon buffers.
  5154. else if (accessor.byteOffset && accessor.byteOffset % BABYLON.VertexBuffer.GetTypeByteLength(accessor.componentType) !== 0) {
  5155. BABYLON.Tools.Warn("Accessor byte offset is not a multiple of component type byte length");
  5156. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  5157. return new BABYLON.VertexBuffer(_this.babylonScene.getEngine(), data, kind, false);
  5158. });
  5159. }
  5160. else {
  5161. var bufferView_1 = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  5162. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync(bufferView_1, kind).then(function (babylonBuffer) {
  5163. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  5164. return new BABYLON.VertexBuffer(_this.babylonScene.getEngine(), babylonBuffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  5165. });
  5166. }
  5167. return accessor._babylonVertexBuffer;
  5168. };
  5169. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, properties, babylonMaterial) {
  5170. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  5171. throw new Error(context + ": Material type not supported");
  5172. }
  5173. var promises = new Array();
  5174. if (properties) {
  5175. if (properties.baseColorFactor) {
  5176. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  5177. babylonMaterial.alpha = properties.baseColorFactor[3];
  5178. }
  5179. else {
  5180. babylonMaterial.albedoColor = BABYLON.Color3.White();
  5181. }
  5182. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  5183. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  5184. if (properties.baseColorTexture) {
  5185. promises.push(this.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  5186. babylonMaterial.albedoTexture = texture;
  5187. }));
  5188. }
  5189. if (properties.metallicRoughnessTexture) {
  5190. promises.push(this.loadTextureInfoAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  5191. babylonMaterial.metallicTexture = texture;
  5192. }));
  5193. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  5194. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  5195. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  5196. }
  5197. }
  5198. return Promise.all(promises).then(function () { });
  5199. };
  5200. /** @hidden */
  5201. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  5202. if (assign === void 0) { assign = function () { }; }
  5203. var extensionPromise = this._extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign);
  5204. if (extensionPromise) {
  5205. return extensionPromise;
  5206. }
  5207. material._babylonData = material._babylonData || {};
  5208. var babylonData = material._babylonData[babylonDrawMode];
  5209. if (!babylonData) {
  5210. this.logOpen(context + " " + (material.name || ""));
  5211. var babylonMaterial = this.createMaterial(context, material, babylonDrawMode);
  5212. babylonData = {
  5213. material: babylonMaterial,
  5214. meshes: [],
  5215. promise: this.loadMaterialPropertiesAsync(context, material, babylonMaterial)
  5216. };
  5217. material._babylonData[babylonDrawMode] = babylonData;
  5218. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  5219. this.logClose();
  5220. }
  5221. babylonData.meshes.push(babylonMesh);
  5222. babylonMesh.onDisposeObservable.addOnce(function () {
  5223. var index = babylonData.meshes.indexOf(babylonMesh);
  5224. if (index !== -1) {
  5225. babylonData.meshes.splice(index, 1);
  5226. }
  5227. });
  5228. assign(babylonData.material);
  5229. return babylonData.promise.then(function () {
  5230. return babylonData.material;
  5231. });
  5232. };
  5233. GLTFLoader.prototype._createDefaultMaterial = function (name, babylonDrawMode) {
  5234. var babylonMaterial = new BABYLON.PBRMaterial(name, this.babylonScene);
  5235. babylonMaterial.sideOrientation = this.babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  5236. babylonMaterial.fillMode = babylonDrawMode;
  5237. babylonMaterial.enableSpecularAntiAliasing = true;
  5238. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  5239. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  5240. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  5241. babylonMaterial.metallic = 1;
  5242. babylonMaterial.roughness = 1;
  5243. return babylonMaterial;
  5244. };
  5245. /**
  5246. * Creates a Babylon material from a glTF material.
  5247. * @param context The context when loading the asset
  5248. * @param material The glTF material property
  5249. * @param babylonDrawMode The draw mode for the Babylon material
  5250. * @returns The Babylon material
  5251. */
  5252. GLTFLoader.prototype.createMaterial = function (context, material, babylonDrawMode) {
  5253. var extensionPromise = this._extensionsCreateMaterial(context, material, babylonDrawMode);
  5254. if (extensionPromise) {
  5255. return extensionPromise;
  5256. }
  5257. var name = material.name || "material" + material.index;
  5258. return this._createDefaultMaterial(name, babylonDrawMode);
  5259. };
  5260. /**
  5261. * Loads properties from a glTF material into a Babylon material.
  5262. * @param context The context when loading the asset
  5263. * @param material The glTF material property
  5264. * @param babylonMaterial The Babylon material
  5265. * @returns A promise that resolves when the load is complete
  5266. */
  5267. GLTFLoader.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  5268. var extensionPromise = this._extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial);
  5269. if (extensionPromise) {
  5270. return extensionPromise;
  5271. }
  5272. var promises = new Array();
  5273. promises.push(this.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  5274. if (material.pbrMetallicRoughness) {
  5275. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context + "/pbrMetallicRoughness", material.pbrMetallicRoughness, babylonMaterial));
  5276. }
  5277. this.loadMaterialAlphaProperties(context, material, babylonMaterial);
  5278. return Promise.all(promises).then(function () { });
  5279. };
  5280. /**
  5281. * Loads the normal, occlusion, and emissive properties from a glTF material into a Babylon material.
  5282. * @param context The context when loading the asset
  5283. * @param material The glTF material property
  5284. * @param babylonMaterial The Babylon material
  5285. * @returns A promise that resolves when the load is complete
  5286. */
  5287. GLTFLoader.prototype.loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  5288. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  5289. throw new Error(context + ": Material type not supported");
  5290. }
  5291. var promises = new Array();
  5292. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  5293. if (material.doubleSided) {
  5294. babylonMaterial.backFaceCulling = false;
  5295. babylonMaterial.twoSidedLighting = true;
  5296. }
  5297. if (material.normalTexture) {
  5298. promises.push(this.loadTextureInfoAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  5299. babylonMaterial.bumpTexture = texture;
  5300. }));
  5301. babylonMaterial.invertNormalMapX = !this.babylonScene.useRightHandedSystem;
  5302. babylonMaterial.invertNormalMapY = this.babylonScene.useRightHandedSystem;
  5303. if (material.normalTexture.scale != undefined) {
  5304. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  5305. }
  5306. }
  5307. if (material.occlusionTexture) {
  5308. promises.push(this.loadTextureInfoAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  5309. babylonMaterial.ambientTexture = texture;
  5310. }));
  5311. babylonMaterial.useAmbientInGrayScale = true;
  5312. if (material.occlusionTexture.strength != undefined) {
  5313. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  5314. }
  5315. }
  5316. if (material.emissiveTexture) {
  5317. promises.push(this.loadTextureInfoAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  5318. babylonMaterial.emissiveTexture = texture;
  5319. }));
  5320. }
  5321. return Promise.all(promises).then(function () { });
  5322. };
  5323. /**
  5324. * Loads the alpha properties from a glTF material into a Babylon material.
  5325. * Must be called after the setting the albedo texture of the Babylon material when the material has an albedo texture.
  5326. * @param context The context when loading the asset
  5327. * @param material The glTF material property
  5328. * @param babylonMaterial The Babylon material
  5329. */
  5330. GLTFLoader.prototype.loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  5331. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  5332. throw new Error(context + ": Material type not supported");
  5333. }
  5334. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  5335. switch (alphaMode) {
  5336. case "OPAQUE" /* OPAQUE */: {
  5337. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  5338. break;
  5339. }
  5340. case "MASK" /* MASK */: {
  5341. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  5342. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  5343. if (babylonMaterial.albedoTexture) {
  5344. babylonMaterial.albedoTexture.hasAlpha = true;
  5345. }
  5346. break;
  5347. }
  5348. case "BLEND" /* BLEND */: {
  5349. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  5350. if (babylonMaterial.albedoTexture) {
  5351. babylonMaterial.albedoTexture.hasAlpha = true;
  5352. babylonMaterial.useAlphaFromAlbedoTexture = true;
  5353. }
  5354. break;
  5355. }
  5356. default: {
  5357. throw new Error(context + "/alphaMode: Invalid value (" + material.alphaMode + ")");
  5358. }
  5359. }
  5360. };
  5361. /**
  5362. * Loads a glTF texture info.
  5363. * @param context The context when loading the asset
  5364. * @param textureInfo The glTF texture info property
  5365. * @param assign A function called synchronously after parsing the glTF properties
  5366. * @returns A promise that resolves with the loaded Babylon texture when the load is complete
  5367. */
  5368. GLTFLoader.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) {
  5369. if (assign === void 0) { assign = function () { }; }
  5370. var extensionPromise = this._extensionsLoadTextureInfoAsync(context, textureInfo, assign);
  5371. if (extensionPromise) {
  5372. return extensionPromise;
  5373. }
  5374. this.logOpen("" + context);
  5375. var texture = ArrayItem.Get(context + "/index", this.gltf.textures, textureInfo.index);
  5376. var promise = this._loadTextureAsync("#/textures/" + textureInfo.index, texture, function (babylonTexture) {
  5377. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  5378. assign(babylonTexture);
  5379. });
  5380. this.logClose();
  5381. return promise;
  5382. };
  5383. GLTFLoader.prototype._loadTextureAsync = function (context, texture, assign) {
  5384. var _this = this;
  5385. if (assign === void 0) { assign = function () { }; }
  5386. var promises = new Array();
  5387. this.logOpen(context + " " + (texture.name || ""));
  5388. var sampler = (texture.sampler == undefined ? GLTFLoader._DefaultSampler : ArrayItem.Get(context + "/sampler", this.gltf.samplers, texture.sampler));
  5389. var samplerData = this._loadSampler("#/samplers/" + sampler.index, sampler);
  5390. var deferred = new BABYLON.Deferred();
  5391. var babylonTexture = new BABYLON.Texture(null, this.babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  5392. if (!_this._disposed) {
  5393. deferred.resolve();
  5394. }
  5395. }, function (message, exception) {
  5396. if (!_this._disposed) {
  5397. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  5398. }
  5399. });
  5400. promises.push(deferred.promise);
  5401. babylonTexture.name = texture.name || "texture" + texture.index;
  5402. babylonTexture.wrapU = samplerData.wrapU;
  5403. babylonTexture.wrapV = samplerData.wrapV;
  5404. var image = ArrayItem.Get(context + "/source", this.gltf.images, texture.source);
  5405. promises.push(this.loadImageAsync("#/images/" + image.index, image).then(function (data) {
  5406. var name = image.uri || _this._fileName + "#image" + image.index;
  5407. var dataUrl = "data:" + _this._uniqueRootUrl + name;
  5408. babylonTexture.updateURL(dataUrl, new Blob([data], { type: image.mimeType }));
  5409. }));
  5410. assign(babylonTexture);
  5411. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  5412. this.logClose();
  5413. return Promise.all(promises).then(function () {
  5414. return babylonTexture;
  5415. });
  5416. };
  5417. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  5418. if (!sampler._data) {
  5419. sampler._data = {
  5420. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  5421. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler),
  5422. wrapU: GLTFLoader._GetTextureWrapMode(context + "/wrapS", sampler.wrapS),
  5423. wrapV: GLTFLoader._GetTextureWrapMode(context + "/wrapT", sampler.wrapT)
  5424. };
  5425. }
  5426. return sampler._data;
  5427. };
  5428. /**
  5429. * Loads a glTF image.
  5430. * @param context The context when loading the asset
  5431. * @param image The glTF image property
  5432. * @returns A promise that resolves with the loaded data when the load is complete
  5433. */
  5434. GLTFLoader.prototype.loadImageAsync = function (context, image) {
  5435. if (!image._data) {
  5436. this.logOpen(context + " " + (image.name || ""));
  5437. if (image.uri) {
  5438. image._data = this.loadUriAsync(context + "/uri", image.uri);
  5439. }
  5440. else {
  5441. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, image.bufferView);
  5442. image._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView);
  5443. }
  5444. this.logClose();
  5445. }
  5446. return image._data;
  5447. };
  5448. /**
  5449. * Loads a glTF uri.
  5450. * @param context The context when loading the asset
  5451. * @param uri The base64 or relative uri
  5452. * @returns A promise that resolves with the loaded data when the load is complete
  5453. */
  5454. GLTFLoader.prototype.loadUriAsync = function (context, uri) {
  5455. var _this = this;
  5456. var extensionPromise = this._extensionsLoadUriAsync(context, uri);
  5457. if (extensionPromise) {
  5458. return extensionPromise;
  5459. }
  5460. if (!GLTFLoader._ValidateUri(uri)) {
  5461. throw new Error(context + ": '" + uri + "' is invalid");
  5462. }
  5463. if (BABYLON.Tools.IsBase64(uri)) {
  5464. var data = new Uint8Array(BABYLON.Tools.DecodeBase64(uri));
  5465. this.log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)");
  5466. return Promise.resolve(data);
  5467. }
  5468. this.log("Loading " + uri);
  5469. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  5470. return new Promise(function (resolve, reject) {
  5471. if (!_this._disposed) {
  5472. var request_1 = BABYLON.Tools.LoadFile(url, function (fileData) {
  5473. if (!_this._disposed) {
  5474. var data = new Uint8Array(fileData);
  5475. _this.log("Loaded " + uri + " (" + data.length + " bytes)");
  5476. resolve(data);
  5477. }
  5478. }, function (event) {
  5479. if (!_this._disposed) {
  5480. if (request_1) {
  5481. request_1._lengthComputable = event.lengthComputable;
  5482. request_1._loaded = event.loaded;
  5483. request_1._total = event.total;
  5484. }
  5485. if (_this._state === BABYLON.GLTFLoaderState.LOADING) {
  5486. try {
  5487. _this._onProgress();
  5488. }
  5489. catch (e) {
  5490. reject(e);
  5491. }
  5492. }
  5493. }
  5494. }, _this.babylonScene.database, true, function (request, exception) {
  5495. if (!_this._disposed) {
  5496. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  5497. }
  5498. });
  5499. _this._requests.push(request_1);
  5500. }
  5501. });
  5502. });
  5503. };
  5504. GLTFLoader.prototype._onProgress = function () {
  5505. if (!this._progressCallback) {
  5506. return;
  5507. }
  5508. var lengthComputable = true;
  5509. var loaded = 0;
  5510. var total = 0;
  5511. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  5512. var request = _a[_i];
  5513. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  5514. return;
  5515. }
  5516. lengthComputable = lengthComputable && request._lengthComputable;
  5517. loaded += request._loaded;
  5518. total += request._total;
  5519. }
  5520. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  5521. };
  5522. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  5523. // Set defaults if undefined
  5524. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  5525. switch (mode) {
  5526. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  5527. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  5528. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  5529. default:
  5530. BABYLON.Tools.Warn(context + ": Invalid value (" + mode + ")");
  5531. return BABYLON.Texture.WRAP_ADDRESSMODE;
  5532. }
  5533. };
  5534. GLTFLoader._GetTextureSamplingMode = function (context, sampler) {
  5535. // Set defaults if undefined
  5536. var magFilter = sampler.magFilter == undefined ? 9729 /* LINEAR */ : sampler.magFilter;
  5537. var minFilter = sampler.minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : sampler.minFilter;
  5538. if (magFilter === 9729 /* LINEAR */) {
  5539. switch (minFilter) {
  5540. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  5541. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  5542. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  5543. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  5544. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  5545. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  5546. default:
  5547. BABYLON.Tools.Warn(context + "/minFilter: Invalid value (" + minFilter + ")");
  5548. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  5549. }
  5550. }
  5551. else {
  5552. if (magFilter !== 9728 /* NEAREST */) {
  5553. BABYLON.Tools.Warn(context + "/magFilter: Invalid value (" + magFilter + ")");
  5554. }
  5555. switch (minFilter) {
  5556. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  5557. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  5558. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  5559. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  5560. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  5561. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  5562. default:
  5563. BABYLON.Tools.Warn(context + "/minFilter: Invalid value (" + minFilter + ")");
  5564. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  5565. }
  5566. }
  5567. };
  5568. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  5569. var buffer = bufferView.buffer;
  5570. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  5571. try {
  5572. switch (componentType) {
  5573. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  5574. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  5575. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  5576. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  5577. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  5578. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  5579. default: throw new Error("Invalid component type " + componentType);
  5580. }
  5581. }
  5582. catch (e) {
  5583. throw new Error(context + ": " + e);
  5584. }
  5585. };
  5586. GLTFLoader._GetNumComponents = function (context, type) {
  5587. switch (type) {
  5588. case "SCALAR": return 1;
  5589. case "VEC2": return 2;
  5590. case "VEC3": return 3;
  5591. case "VEC4": return 4;
  5592. case "MAT2": return 4;
  5593. case "MAT3": return 9;
  5594. case "MAT4": return 16;
  5595. }
  5596. throw new Error(context + ": Invalid type (" + type + ")");
  5597. };
  5598. GLTFLoader._ValidateUri = function (uri) {
  5599. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  5600. };
  5601. GLTFLoader._GetDrawMode = function (context, mode) {
  5602. if (mode == undefined) {
  5603. mode = 4 /* TRIANGLES */;
  5604. }
  5605. switch (mode) {
  5606. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  5607. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  5608. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  5609. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  5610. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  5611. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  5612. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  5613. }
  5614. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  5615. };
  5616. GLTFLoader.prototype._compileMaterialsAsync = function () {
  5617. var _this = this;
  5618. this._parent._startPerformanceCounter("Compile materials");
  5619. var promises = new Array();
  5620. if (this.gltf.materials) {
  5621. for (var _i = 0, _a = this.gltf.materials; _i < _a.length; _i++) {
  5622. var material = _a[_i];
  5623. if (material._babylonData) {
  5624. for (var babylonDrawMode in material._babylonData) {
  5625. var babylonData = material._babylonData[babylonDrawMode];
  5626. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  5627. var babylonMesh = _c[_b];
  5628. // Ensure nonUniformScaling is set if necessary.
  5629. babylonMesh.computeWorldMatrix(true);
  5630. var babylonMaterial = babylonData.material;
  5631. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  5632. if (this._parent.useClipPlane) {
  5633. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  5634. }
  5635. }
  5636. }
  5637. }
  5638. }
  5639. }
  5640. return Promise.all(promises).then(function () {
  5641. _this._parent._endPerformanceCounter("Compile materials");
  5642. });
  5643. };
  5644. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  5645. var _this = this;
  5646. this._parent._startPerformanceCounter("Compile shadow generators");
  5647. var promises = new Array();
  5648. var lights = this.babylonScene.lights;
  5649. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  5650. var light = lights_1[_i];
  5651. var generator = light.getShadowGenerator();
  5652. if (generator) {
  5653. promises.push(generator.forceCompilationAsync());
  5654. }
  5655. }
  5656. return Promise.all(promises).then(function () {
  5657. _this._parent._endPerformanceCounter("Compile shadow generators");
  5658. });
  5659. };
  5660. GLTFLoader.prototype._forEachExtensions = function (action) {
  5661. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  5662. var name_4 = _a[_i];
  5663. var extension = this._extensions[name_4];
  5664. if (extension.enabled) {
  5665. action(extension);
  5666. }
  5667. }
  5668. };
  5669. GLTFLoader.prototype._applyExtensions = function (property, actionAsync) {
  5670. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  5671. var name_5 = _a[_i];
  5672. var extension = this._extensions[name_5];
  5673. if (extension.enabled) {
  5674. var loaderProperty = property;
  5675. loaderProperty._activeLoaderExtensions = loaderProperty._activeLoaderExtensions || {};
  5676. var activeLoaderExtensions = loaderProperty._activeLoaderExtensions;
  5677. if (!activeLoaderExtensions[name_5]) {
  5678. activeLoaderExtensions[name_5] = true;
  5679. try {
  5680. var result = actionAsync(extension);
  5681. if (result) {
  5682. return result;
  5683. }
  5684. }
  5685. finally {
  5686. delete activeLoaderExtensions[name_5];
  5687. }
  5688. }
  5689. }
  5690. }
  5691. return null;
  5692. };
  5693. GLTFLoader.prototype._extensionsOnLoading = function () {
  5694. this._forEachExtensions(function (extension) { return extension.onLoading && extension.onLoading(); });
  5695. };
  5696. GLTFLoader.prototype._extensionsOnReady = function () {
  5697. this._forEachExtensions(function (extension) { return extension.onReady && extension.onReady(); });
  5698. };
  5699. GLTFLoader.prototype._extensionsLoadSceneAsync = function (context, scene) {
  5700. return this._applyExtensions(scene, function (extension) { return extension.loadSceneAsync && extension.loadSceneAsync(context, scene); });
  5701. };
  5702. GLTFLoader.prototype._extensionsLoadNodeAsync = function (context, node, assign) {
  5703. return this._applyExtensions(node, function (extension) { return extension.loadNodeAsync && extension.loadNodeAsync(context, node, assign); });
  5704. };
  5705. GLTFLoader.prototype._extensionsLoadCameraAsync = function (context, camera, assign) {
  5706. return this._applyExtensions(camera, function (extension) { return extension.loadCameraAsync && extension.loadCameraAsync(context, camera, assign); });
  5707. };
  5708. GLTFLoader.prototype._extensionsLoadVertexDataAsync = function (context, primitive, babylonMesh) {
  5709. return this._applyExtensions(primitive, function (extension) { return extension._loadVertexDataAsync && extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  5710. };
  5711. GLTFLoader.prototype._extensionsLoadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  5712. return this._applyExtensions(material, function (extension) { return extension._loadMaterialAsync && extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  5713. };
  5714. GLTFLoader.prototype._extensionsCreateMaterial = function (context, material, babylonDrawMode) {
  5715. return this._applyExtensions({}, function (extension) { return extension.createMaterial && extension.createMaterial(context, material, babylonDrawMode); });
  5716. };
  5717. GLTFLoader.prototype._extensionsLoadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  5718. return this._applyExtensions(material, function (extension) { return extension.loadMaterialPropertiesAsync && extension.loadMaterialPropertiesAsync(context, material, babylonMaterial); });
  5719. };
  5720. GLTFLoader.prototype._extensionsLoadTextureInfoAsync = function (context, textureInfo, assign) {
  5721. return this._applyExtensions(textureInfo, function (extension) { return extension.loadTextureInfoAsync && extension.loadTextureInfoAsync(context, textureInfo, assign); });
  5722. };
  5723. GLTFLoader.prototype._extensionsLoadAnimationAsync = function (context, animation) {
  5724. return this._applyExtensions(animation, function (extension) { return extension.loadAnimationAsync && extension.loadAnimationAsync(context, animation); });
  5725. };
  5726. GLTFLoader.prototype._extensionsLoadUriAsync = function (context, uri) {
  5727. return this._applyExtensions({}, function (extension) { return extension._loadUriAsync && extension._loadUriAsync(context, uri); });
  5728. };
  5729. /**
  5730. * Helper method called by a loader extension to load an glTF extension.
  5731. * @param context The context when loading the asset
  5732. * @param property The glTF property to load the extension from
  5733. * @param extensionName The name of the extension to load
  5734. * @param actionAsync The action to run
  5735. * @returns The promise returned by actionAsync or null if the extension does not exist
  5736. */
  5737. GLTFLoader.LoadExtensionAsync = function (context, property, extensionName, actionAsync) {
  5738. if (!property.extensions) {
  5739. return null;
  5740. }
  5741. var extensions = property.extensions;
  5742. var extension = extensions[extensionName];
  5743. if (!extension) {
  5744. return null;
  5745. }
  5746. return actionAsync(context + "/extensions/" + extensionName, extension);
  5747. };
  5748. /**
  5749. * Helper method called by a loader extension to load a glTF extra.
  5750. * @param context The context when loading the asset
  5751. * @param property The glTF property to load the extra from
  5752. * @param extensionName The name of the extension to load
  5753. * @param actionAsync The action to run
  5754. * @returns The promise returned by actionAsync or null if the extra does not exist
  5755. */
  5756. GLTFLoader.LoadExtraAsync = function (context, property, extensionName, actionAsync) {
  5757. if (!property.extras) {
  5758. return null;
  5759. }
  5760. var extras = property.extras;
  5761. var extra = extras[extensionName];
  5762. if (!extra) {
  5763. return null;
  5764. }
  5765. return actionAsync(context + "/extras/" + extensionName, extra);
  5766. };
  5767. /**
  5768. * Increments the indentation level and logs a message.
  5769. * @param message The message to log
  5770. */
  5771. GLTFLoader.prototype.logOpen = function (message) {
  5772. this._parent._logOpen(message);
  5773. };
  5774. /**
  5775. * Decrements the indentation level.
  5776. */
  5777. GLTFLoader.prototype.logClose = function () {
  5778. this._parent._logClose();
  5779. };
  5780. /**
  5781. * Logs a message
  5782. * @param message The message to log
  5783. */
  5784. GLTFLoader.prototype.log = function (message) {
  5785. this._parent._log(message);
  5786. };
  5787. /**
  5788. * Starts a performance counter.
  5789. * @param counterName The name of the performance counter
  5790. */
  5791. GLTFLoader.prototype.startPerformanceCounter = function (counterName) {
  5792. this._parent._startPerformanceCounter(counterName);
  5793. };
  5794. /**
  5795. * Ends a performance counter.
  5796. * @param counterName The name of the performance counter
  5797. */
  5798. GLTFLoader.prototype.endPerformanceCounter = function (counterName) {
  5799. this._parent._endPerformanceCounter(counterName);
  5800. };
  5801. GLTFLoader._DefaultSampler = { index: -1 };
  5802. GLTFLoader._ExtensionNames = new Array();
  5803. GLTFLoader._ExtensionFactories = {};
  5804. return GLTFLoader;
  5805. }());
  5806. GLTF2.GLTFLoader = GLTFLoader;
  5807. BABYLON.GLTFFileLoader._CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  5808. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5809. })(BABYLON || (BABYLON = {}));
  5810. //# sourceMappingURL=babylon.glTFLoader.js.map
  5811. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  5812. var BABYLON;
  5813. (function (BABYLON) {
  5814. var GLTF2;
  5815. (function (GLTF2) {
  5816. var Loader;
  5817. (function (Loader) {
  5818. var Extensions;
  5819. (function (Extensions) {
  5820. var NAME = "MSFT_lod";
  5821. /**
  5822. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  5823. */
  5824. var MSFT_lod = /** @class */ (function () {
  5825. /** @hidden */
  5826. function MSFT_lod(loader) {
  5827. /** The name of this extension. */
  5828. this.name = NAME;
  5829. /** Defines whether this extension is enabled. */
  5830. this.enabled = true;
  5831. /**
  5832. * Maximum number of LODs to load, starting from the lowest LOD.
  5833. */
  5834. this.maxLODsToLoad = Number.MAX_VALUE;
  5835. /**
  5836. * Observable raised when all node LODs of one level are loaded.
  5837. * The event data is the index of the loaded LOD starting from zero.
  5838. * Dispose the loader to cancel the loading of the next level of LODs.
  5839. */
  5840. this.onNodeLODsLoadedObservable = new BABYLON.Observable();
  5841. /**
  5842. * Observable raised when all material LODs of one level are loaded.
  5843. * The event data is the index of the loaded LOD starting from zero.
  5844. * Dispose the loader to cancel the loading of the next level of LODs.
  5845. */
  5846. this.onMaterialLODsLoadedObservable = new BABYLON.Observable();
  5847. this._nodeIndexLOD = null;
  5848. this._nodeSignalLODs = new Array();
  5849. this._nodePromiseLODs = new Array();
  5850. this._materialIndexLOD = null;
  5851. this._materialSignalLODs = new Array();
  5852. this._materialPromiseLODs = new Array();
  5853. this._loader = loader;
  5854. }
  5855. /** @hidden */
  5856. MSFT_lod.prototype.dispose = function () {
  5857. delete this._loader;
  5858. this._nodeIndexLOD = null;
  5859. this._nodeSignalLODs.length = 0;
  5860. this._nodePromiseLODs.length = 0;
  5861. this._materialIndexLOD = null;
  5862. this._materialSignalLODs.length = 0;
  5863. this._materialPromiseLODs.length = 0;
  5864. this.onMaterialLODsLoadedObservable.clear();
  5865. this.onNodeLODsLoadedObservable.clear();
  5866. };
  5867. /** @hidden */
  5868. MSFT_lod.prototype.onReady = function () {
  5869. var _this = this;
  5870. var _loop_1 = function (indexLOD) {
  5871. var promise = Promise.all(this_1._nodePromiseLODs[indexLOD]).then(function () {
  5872. if (indexLOD !== 0) {
  5873. _this._loader.endPerformanceCounter("Node LOD " + indexLOD);
  5874. }
  5875. _this._loader.log("Loaded node LOD " + indexLOD);
  5876. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  5877. if (indexLOD !== _this._nodePromiseLODs.length - 1) {
  5878. _this._loader.startPerformanceCounter("Node LOD " + (indexLOD + 1));
  5879. if (_this._nodeSignalLODs[indexLOD]) {
  5880. _this._nodeSignalLODs[indexLOD].resolve();
  5881. }
  5882. }
  5883. });
  5884. this_1._loader._completePromises.push(promise);
  5885. };
  5886. var this_1 = this;
  5887. for (var indexLOD = 0; indexLOD < this._nodePromiseLODs.length; indexLOD++) {
  5888. _loop_1(indexLOD);
  5889. }
  5890. var _loop_2 = function (indexLOD) {
  5891. var promise = Promise.all(this_2._materialPromiseLODs[indexLOD]).then(function () {
  5892. if (indexLOD !== 0) {
  5893. _this._loader.endPerformanceCounter("Material LOD " + indexLOD);
  5894. }
  5895. _this._loader.log("Loaded material LOD " + indexLOD);
  5896. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  5897. if (indexLOD !== _this._materialPromiseLODs.length - 1) {
  5898. _this._loader.startPerformanceCounter("Material LOD " + (indexLOD + 1));
  5899. if (_this._materialSignalLODs[indexLOD]) {
  5900. _this._materialSignalLODs[indexLOD].resolve();
  5901. }
  5902. }
  5903. });
  5904. this_2._loader._completePromises.push(promise);
  5905. };
  5906. var this_2 = this;
  5907. for (var indexLOD = 0; indexLOD < this._materialPromiseLODs.length; indexLOD++) {
  5908. _loop_2(indexLOD);
  5909. }
  5910. };
  5911. /** @hidden */
  5912. MSFT_lod.prototype.loadNodeAsync = function (context, node, assign) {
  5913. var _this = this;
  5914. return GLTF2.GLTFLoader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  5915. var firstPromise;
  5916. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader.gltf.nodes, extension.ids);
  5917. _this._loader.logOpen("" + extensionContext);
  5918. var _loop_3 = function (indexLOD) {
  5919. var nodeLOD = nodeLODs[indexLOD];
  5920. if (indexLOD !== 0) {
  5921. _this._nodeIndexLOD = indexLOD;
  5922. _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new BABYLON.Deferred();
  5923. }
  5924. var promise = _this._loader.loadNodeAsync("#/nodes/" + nodeLOD.index, nodeLOD).then(function (babylonMesh) {
  5925. if (indexLOD !== 0) {
  5926. // TODO: should not rely on _babylonMesh
  5927. var previousNodeLOD = nodeLODs[indexLOD - 1];
  5928. if (previousNodeLOD._babylonMesh) {
  5929. previousNodeLOD._babylonMesh.dispose();
  5930. delete previousNodeLOD._babylonMesh;
  5931. _this._disposeUnusedMaterials();
  5932. }
  5933. }
  5934. return babylonMesh;
  5935. });
  5936. if (indexLOD === 0) {
  5937. firstPromise = promise;
  5938. }
  5939. else {
  5940. _this._nodeIndexLOD = null;
  5941. }
  5942. _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || [];
  5943. _this._nodePromiseLODs[indexLOD].push(promise);
  5944. };
  5945. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  5946. _loop_3(indexLOD);
  5947. }
  5948. _this._loader.logClose();
  5949. return firstPromise;
  5950. });
  5951. };
  5952. /** @hidden */
  5953. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  5954. var _this = this;
  5955. // Don't load material LODs if already loading a node LOD.
  5956. if (this._nodeIndexLOD) {
  5957. return null;
  5958. }
  5959. return GLTF2.GLTFLoader.LoadExtensionAsync(context, material, this.name, function (extensionContext, extension) {
  5960. var firstPromise;
  5961. var materialLODs = _this._getLODs(extensionContext, material, _this._loader.gltf.materials, extension.ids);
  5962. _this._loader.logOpen("" + extensionContext);
  5963. var _loop_4 = function (indexLOD) {
  5964. var materialLOD = materialLODs[indexLOD];
  5965. if (indexLOD !== 0) {
  5966. _this._materialIndexLOD = indexLOD;
  5967. }
  5968. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD.index, materialLOD, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  5969. if (indexLOD === 0) {
  5970. assign(babylonMaterial);
  5971. }
  5972. }).then(function (babylonMaterial) {
  5973. if (indexLOD !== 0) {
  5974. assign(babylonMaterial);
  5975. // TODO: should not rely on _babylonData
  5976. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  5977. if (previousBabylonDataLOD[babylonDrawMode]) {
  5978. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  5979. delete previousBabylonDataLOD[babylonDrawMode];
  5980. }
  5981. }
  5982. return babylonMaterial;
  5983. });
  5984. if (indexLOD === 0) {
  5985. firstPromise = promise;
  5986. }
  5987. else {
  5988. _this._materialIndexLOD = null;
  5989. }
  5990. _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || [];
  5991. _this._materialPromiseLODs[indexLOD].push(promise);
  5992. };
  5993. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  5994. _loop_4(indexLOD);
  5995. }
  5996. _this._loader.logClose();
  5997. return firstPromise;
  5998. });
  5999. };
  6000. /** @hidden */
  6001. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  6002. var _this = this;
  6003. // Defer the loading of uris if loading a material or node LOD.
  6004. if (this._materialIndexLOD !== null) {
  6005. this._loader.log("deferred");
  6006. var previousIndexLOD = this._materialIndexLOD - 1;
  6007. this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  6008. return this._materialSignalLODs[previousIndexLOD].promise.then(function () {
  6009. return _this._loader.loadUriAsync(context, uri);
  6010. });
  6011. }
  6012. else if (this._nodeIndexLOD !== null) {
  6013. this._loader.log("deferred");
  6014. var previousIndexLOD = this._nodeIndexLOD - 1;
  6015. this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  6016. return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () {
  6017. return _this._loader.loadUriAsync(context, uri);
  6018. });
  6019. }
  6020. return null;
  6021. };
  6022. /**
  6023. * Gets an array of LOD properties from lowest to highest.
  6024. */
  6025. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  6026. if (this.maxLODsToLoad <= 0) {
  6027. throw new Error("maxLODsToLoad must be greater than zero");
  6028. }
  6029. var properties = new Array();
  6030. for (var i = ids.length - 1; i >= 0; i--) {
  6031. properties.push(GLTF2.ArrayItem.Get(context + "/ids/" + ids[i], array, ids[i]));
  6032. if (properties.length === this.maxLODsToLoad) {
  6033. return properties;
  6034. }
  6035. }
  6036. properties.push(property);
  6037. return properties;
  6038. };
  6039. MSFT_lod.prototype._disposeUnusedMaterials = function () {
  6040. // TODO: should not rely on _babylonData
  6041. var materials = this._loader.gltf.materials;
  6042. if (materials) {
  6043. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  6044. var material = materials_1[_i];
  6045. if (material._babylonData) {
  6046. for (var drawMode in material._babylonData) {
  6047. var babylonData = material._babylonData[drawMode];
  6048. if (babylonData.meshes.length === 0) {
  6049. babylonData.material.dispose(false, true);
  6050. delete material._babylonData[drawMode];
  6051. }
  6052. }
  6053. }
  6054. }
  6055. }
  6056. };
  6057. return MSFT_lod;
  6058. }());
  6059. Extensions.MSFT_lod = MSFT_lod;
  6060. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_lod(loader); });
  6061. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  6062. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  6063. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  6064. })(BABYLON || (BABYLON = {}));
  6065. //# sourceMappingURL=MSFT_lod.js.map
  6066. var BABYLON;
  6067. (function (BABYLON) {
  6068. var GLTF2;
  6069. (function (GLTF2) {
  6070. var Loader;
  6071. (function (Loader) {
  6072. var Extensions;
  6073. (function (Extensions) {
  6074. var NAME = "MSFT_minecraftMesh";
  6075. /** @hidden */
  6076. var MSFT_minecraftMesh = /** @class */ (function () {
  6077. function MSFT_minecraftMesh(loader) {
  6078. this.name = NAME;
  6079. this.enabled = true;
  6080. this._loader = loader;
  6081. }
  6082. MSFT_minecraftMesh.prototype.dispose = function () {
  6083. delete this._loader;
  6084. };
  6085. MSFT_minecraftMesh.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  6086. var _this = this;
  6087. return GLTF2.GLTFLoader.LoadExtraAsync(context, material, this.name, function (extraContext, extra) {
  6088. if (extra) {
  6089. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  6090. throw new Error(extraContext + ": Material type not supported");
  6091. }
  6092. var promise = _this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);
  6093. if (babylonMaterial.needAlphaBlending()) {
  6094. babylonMaterial.forceDepthWrite = true;
  6095. babylonMaterial.separateCullingPass = true;
  6096. }
  6097. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  6098. babylonMaterial.twoSidedLighting = true;
  6099. return promise;
  6100. }
  6101. return null;
  6102. });
  6103. };
  6104. return MSFT_minecraftMesh;
  6105. }());
  6106. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  6107. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  6108. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  6109. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  6110. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  6111. })(BABYLON || (BABYLON = {}));
  6112. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  6113. var BABYLON;
  6114. (function (BABYLON) {
  6115. var GLTF2;
  6116. (function (GLTF2) {
  6117. var Loader;
  6118. (function (Loader) {
  6119. var Extensions;
  6120. (function (Extensions) {
  6121. var NAME = "MSFT_sRGBFactors";
  6122. /** @hidden */
  6123. var MSFT_sRGBFactors = /** @class */ (function () {
  6124. function MSFT_sRGBFactors(loader) {
  6125. this.name = NAME;
  6126. this.enabled = true;
  6127. this._loader = loader;
  6128. }
  6129. MSFT_sRGBFactors.prototype.dispose = function () {
  6130. delete this._loader;
  6131. };
  6132. MSFT_sRGBFactors.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  6133. var _this = this;
  6134. return GLTF2.GLTFLoader.LoadExtraAsync(context, material, this.name, function (extraContext, extra) {
  6135. if (extra) {
  6136. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  6137. throw new Error(extraContext + ": Material type not supported");
  6138. }
  6139. var promise = _this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);
  6140. if (!babylonMaterial.albedoTexture) {
  6141. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  6142. }
  6143. if (!babylonMaterial.reflectivityTexture) {
  6144. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  6145. }
  6146. return promise;
  6147. }
  6148. return null;
  6149. });
  6150. };
  6151. return MSFT_sRGBFactors;
  6152. }());
  6153. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  6154. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  6155. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  6156. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  6157. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  6158. })(BABYLON || (BABYLON = {}));
  6159. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  6160. var BABYLON;
  6161. (function (BABYLON) {
  6162. var GLTF2;
  6163. (function (GLTF2) {
  6164. var Loader;
  6165. (function (Loader) {
  6166. var Extensions;
  6167. (function (Extensions) {
  6168. var NAME = "MSFT_audio_emitter";
  6169. /**
  6170. * [Specification](https://github.com/najadojo/glTF/tree/MSFT_audio_emitter/extensions/2.0/Vendor/MSFT_audio_emitter)
  6171. */
  6172. var MSFT_audio_emitter = /** @class */ (function () {
  6173. /** @hidden */
  6174. function MSFT_audio_emitter(loader) {
  6175. /** The name of this extension. */
  6176. this.name = NAME;
  6177. /** Defines whether this extension is enabled. */
  6178. this.enabled = true;
  6179. this._loader = loader;
  6180. }
  6181. /** @hidden */
  6182. MSFT_audio_emitter.prototype.dispose = function () {
  6183. delete this._loader;
  6184. delete this._clips;
  6185. delete this._emitters;
  6186. };
  6187. /** @hidden */
  6188. MSFT_audio_emitter.prototype.onLoading = function () {
  6189. var extensions = this._loader.gltf.extensions;
  6190. if (extensions && extensions[this.name]) {
  6191. var extension = extensions[this.name];
  6192. this._clips = extension.clips;
  6193. this._emitters = extension.emitters;
  6194. GLTF2.ArrayItem.Assign(this._clips);
  6195. GLTF2.ArrayItem.Assign(this._emitters);
  6196. }
  6197. };
  6198. /** @hidden */
  6199. MSFT_audio_emitter.prototype.loadSceneAsync = function (context, scene) {
  6200. var _this = this;
  6201. return GLTF2.GLTFLoader.LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) {
  6202. var promises = new Array();
  6203. promises.push(_this._loader.loadSceneAsync(context, scene));
  6204. for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) {
  6205. var emitterIndex = _a[_i];
  6206. var emitter = GLTF2.ArrayItem.Get(extensionContext + "/emitters", _this._emitters, emitterIndex);
  6207. if (emitter.refDistance != undefined || emitter.maxDistance != undefined || emitter.rolloffFactor != undefined ||
  6208. emitter.distanceModel != undefined || emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  6209. throw new Error(extensionContext + ": Direction or Distance properties are not allowed on emitters attached to a scene");
  6210. }
  6211. promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter.index, emitter));
  6212. }
  6213. return Promise.all(promises).then(function () { });
  6214. });
  6215. };
  6216. /** @hidden */
  6217. MSFT_audio_emitter.prototype.loadNodeAsync = function (context, node, assign) {
  6218. var _this = this;
  6219. return GLTF2.GLTFLoader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  6220. var promises = new Array();
  6221. return _this._loader.loadNodeAsync(extensionContext, node, function (babylonMesh) {
  6222. var _loop_1 = function (emitterIndex) {
  6223. var emitter = GLTF2.ArrayItem.Get(extensionContext + "/emitters", _this._emitters, emitterIndex);
  6224. promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter.index, emitter).then(function () {
  6225. for (var _i = 0, _a = emitter._babylonSounds; _i < _a.length; _i++) {
  6226. var sound = _a[_i];
  6227. sound.attachToMesh(babylonMesh);
  6228. if (emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  6229. sound.setLocalDirectionToMesh(BABYLON.Vector3.Forward());
  6230. sound.setDirectionalCone(2 * BABYLON.Tools.ToDegrees(emitter.innerAngle == undefined ? Math.PI : emitter.innerAngle), 2 * BABYLON.Tools.ToDegrees(emitter.outerAngle == undefined ? Math.PI : emitter.outerAngle), 0);
  6231. }
  6232. }
  6233. }));
  6234. };
  6235. for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) {
  6236. var emitterIndex = _a[_i];
  6237. _loop_1(emitterIndex);
  6238. }
  6239. assign(babylonMesh);
  6240. }).then(function (babylonMesh) {
  6241. return Promise.all(promises).then(function () {
  6242. return babylonMesh;
  6243. });
  6244. });
  6245. });
  6246. };
  6247. /** @hidden */
  6248. MSFT_audio_emitter.prototype.loadAnimationAsync = function (context, animation) {
  6249. var _this = this;
  6250. return GLTF2.GLTFLoader.LoadExtensionAsync(context, animation, this.name, function (extensionContext, extension) {
  6251. return _this._loader.loadAnimationAsync(context, animation).then(function (babylonAnimationGroup) {
  6252. var promises = new Array();
  6253. GLTF2.ArrayItem.Assign(extension.events);
  6254. for (var _i = 0, _a = extension.events; _i < _a.length; _i++) {
  6255. var event_1 = _a[_i];
  6256. promises.push(_this._loadAnimationEventAsync(extensionContext + "/events/" + event_1.index, context, animation, event_1, babylonAnimationGroup));
  6257. }
  6258. return Promise.all(promises).then(function () {
  6259. return babylonAnimationGroup;
  6260. });
  6261. });
  6262. });
  6263. };
  6264. MSFT_audio_emitter.prototype._loadClipAsync = function (context, clip) {
  6265. if (clip._objectURL) {
  6266. return clip._objectURL;
  6267. }
  6268. var promise;
  6269. if (clip.uri) {
  6270. promise = this._loader.loadUriAsync(context, clip.uri);
  6271. }
  6272. else {
  6273. var bufferView = GLTF2.ArrayItem.Get(context + "/bufferView", this._loader.gltf.bufferViews, clip.bufferView);
  6274. promise = this._loader.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView);
  6275. }
  6276. clip._objectURL = promise.then(function (data) {
  6277. return URL.createObjectURL(new Blob([data], { type: clip.mimeType }));
  6278. });
  6279. return clip._objectURL;
  6280. };
  6281. MSFT_audio_emitter.prototype._loadEmitterAsync = function (context, emitter) {
  6282. var _this = this;
  6283. emitter._babylonSounds = emitter._babylonSounds || [];
  6284. if (!emitter._babylonData) {
  6285. var clipPromises = new Array();
  6286. var name_1 = emitter.name || "emitter" + emitter.index;
  6287. var options_1 = {
  6288. loop: false,
  6289. autoplay: false,
  6290. volume: emitter.volume == undefined ? 1 : emitter.volume,
  6291. };
  6292. var _loop_2 = function (i) {
  6293. var clipContext = "#/extensions/" + this_1.name + "/clips";
  6294. var clip = GLTF2.ArrayItem.Get(clipContext, this_1._clips, emitter.clips[i].clip);
  6295. clipPromises.push(this_1._loadClipAsync(clipContext + "/" + emitter.clips[i].clip, clip).then(function (objectURL) {
  6296. var sound = emitter._babylonSounds[i] = new BABYLON.Sound(name_1, objectURL, _this._loader.babylonScene, null, options_1);
  6297. sound.refDistance = emitter.refDistance || 1;
  6298. sound.maxDistance = emitter.maxDistance || 256;
  6299. sound.rolloffFactor = emitter.rolloffFactor || 1;
  6300. sound.distanceModel = emitter.distanceModel || 'exponential';
  6301. sound._positionInEmitterSpace = true;
  6302. }));
  6303. };
  6304. var this_1 = this;
  6305. for (var i = 0; i < emitter.clips.length; i++) {
  6306. _loop_2(i);
  6307. }
  6308. var promise = Promise.all(clipPromises).then(function () {
  6309. var weights = emitter.clips.map(function (clip) { return clip.weight || 1; });
  6310. var weightedSound = new BABYLON.WeightedSound(emitter.loop || false, emitter._babylonSounds, weights);
  6311. if (emitter.innerAngle) {
  6312. weightedSound.directionalConeInnerAngle = 2 * BABYLON.Tools.ToDegrees(emitter.innerAngle);
  6313. }
  6314. if (emitter.outerAngle) {
  6315. weightedSound.directionalConeOuterAngle = 2 * BABYLON.Tools.ToDegrees(emitter.outerAngle);
  6316. }
  6317. if (emitter.volume) {
  6318. weightedSound.volume = emitter.volume;
  6319. }
  6320. emitter._babylonData.sound = weightedSound;
  6321. });
  6322. emitter._babylonData = {
  6323. loaded: promise
  6324. };
  6325. }
  6326. return emitter._babylonData.loaded;
  6327. };
  6328. MSFT_audio_emitter.prototype._getEventAction = function (context, sound, action, time, startOffset) {
  6329. switch (action) {
  6330. case "play" /* play */: {
  6331. return function (currentFrame) {
  6332. var frameOffset = (startOffset || 0) + (currentFrame - time);
  6333. sound.play(frameOffset);
  6334. };
  6335. }
  6336. case "stop" /* stop */: {
  6337. return function (currentFrame) {
  6338. sound.stop();
  6339. };
  6340. }
  6341. case "pause" /* pause */: {
  6342. return function (currentFrame) {
  6343. sound.pause();
  6344. };
  6345. }
  6346. default: {
  6347. throw new Error(context + ": Unsupported action " + action);
  6348. }
  6349. }
  6350. };
  6351. MSFT_audio_emitter.prototype._loadAnimationEventAsync = function (context, animationContext, animation, event, babylonAnimationGroup) {
  6352. var _this = this;
  6353. if (babylonAnimationGroup.targetedAnimations.length == 0) {
  6354. return Promise.resolve();
  6355. }
  6356. var babylonAnimation = babylonAnimationGroup.targetedAnimations[0];
  6357. var emitterIndex = event.emitter;
  6358. var emitter = GLTF2.ArrayItem.Get("#/extensions/" + this.name + "/emitters", this._emitters, emitterIndex);
  6359. return this._loadEmitterAsync(context, emitter).then(function () {
  6360. var sound = emitter._babylonData.sound;
  6361. if (sound) {
  6362. var babylonAnimationEvent = new BABYLON.AnimationEvent(event.time, _this._getEventAction(context, sound, event.action, event.time, event.startOffset));
  6363. babylonAnimation.animation.addEvent(babylonAnimationEvent);
  6364. // Make sure all started audio stops when this animation is terminated.
  6365. babylonAnimationGroup.onAnimationGroupEndObservable.add(function () {
  6366. sound.stop();
  6367. });
  6368. babylonAnimationGroup.onAnimationGroupPauseObservable.add(function () {
  6369. sound.pause();
  6370. });
  6371. }
  6372. });
  6373. };
  6374. return MSFT_audio_emitter;
  6375. }());
  6376. Extensions.MSFT_audio_emitter = MSFT_audio_emitter;
  6377. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_audio_emitter(loader); });
  6378. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  6379. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  6380. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  6381. })(BABYLON || (BABYLON = {}));
  6382. //# sourceMappingURL=MSFT_audio_emitter.js.map
  6383. var BABYLON;
  6384. (function (BABYLON) {
  6385. var GLTF2;
  6386. (function (GLTF2) {
  6387. var Loader;
  6388. (function (Loader) {
  6389. var Extensions;
  6390. (function (Extensions) {
  6391. var NAME = "KHR_draco_mesh_compression";
  6392. /**
  6393. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  6394. */
  6395. var KHR_draco_mesh_compression = /** @class */ (function () {
  6396. /** @hidden */
  6397. function KHR_draco_mesh_compression(loader) {
  6398. /** The name of this extension. */
  6399. this.name = NAME;
  6400. /** Defines whether this extension is enabled. */
  6401. this.enabled = BABYLON.DracoCompression.DecoderAvailable;
  6402. this._loader = loader;
  6403. }
  6404. /** @hidden */
  6405. KHR_draco_mesh_compression.prototype.dispose = function () {
  6406. if (this._dracoCompression) {
  6407. this._dracoCompression.dispose();
  6408. delete this._dracoCompression;
  6409. }
  6410. delete this._loader;
  6411. };
  6412. /** @hidden */
  6413. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  6414. var _this = this;
  6415. return GLTF2.GLTFLoader.LoadExtensionAsync(context, primitive, this.name, function (extensionContext, extension) {
  6416. if (primitive.mode != undefined) {
  6417. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  6418. primitive.mode !== 4 /* TRIANGLES */) {
  6419. throw new Error(context + ": Unsupported mode " + primitive.mode);
  6420. }
  6421. // TODO: handle triangle strips
  6422. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  6423. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  6424. }
  6425. }
  6426. var attributes = {};
  6427. var loadAttribute = function (name, kind) {
  6428. var uniqueId = extension.attributes[name];
  6429. if (uniqueId == undefined) {
  6430. return;
  6431. }
  6432. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  6433. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  6434. babylonMesh._delayInfo.push(kind);
  6435. }
  6436. attributes[kind] = uniqueId;
  6437. };
  6438. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  6439. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  6440. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  6441. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  6442. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  6443. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  6444. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  6445. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  6446. var bufferView = GLTF2.ArrayItem.Get(extensionContext, _this._loader.gltf.bufferViews, extension.bufferView);
  6447. if (!bufferView._dracoBabylonGeometry) {
  6448. bufferView._dracoBabylonGeometry = _this._loader.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  6449. if (!_this._dracoCompression) {
  6450. _this._dracoCompression = new BABYLON.DracoCompression();
  6451. }
  6452. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  6453. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader.babylonScene);
  6454. babylonVertexData.applyToGeometry(babylonGeometry);
  6455. return babylonGeometry;
  6456. }).catch(function (error) {
  6457. throw new Error(context + ": " + error.message);
  6458. });
  6459. });
  6460. }
  6461. return bufferView._dracoBabylonGeometry;
  6462. });
  6463. };
  6464. return KHR_draco_mesh_compression;
  6465. }());
  6466. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  6467. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  6468. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  6469. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  6470. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  6471. })(BABYLON || (BABYLON = {}));
  6472. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  6473. var BABYLON;
  6474. (function (BABYLON) {
  6475. var GLTF2;
  6476. (function (GLTF2) {
  6477. var Loader;
  6478. (function (Loader) {
  6479. var Extensions;
  6480. (function (Extensions) {
  6481. var NAME = "KHR_materials_pbrSpecularGlossiness";
  6482. /**
  6483. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  6484. */
  6485. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function () {
  6486. /** @hidden */
  6487. function KHR_materials_pbrSpecularGlossiness(loader) {
  6488. /** The name of this extension. */
  6489. this.name = NAME;
  6490. /** Defines whether this extension is enabled. */
  6491. this.enabled = true;
  6492. this._loader = loader;
  6493. }
  6494. /** @hidden */
  6495. KHR_materials_pbrSpecularGlossiness.prototype.dispose = function () {
  6496. delete this._loader;
  6497. };
  6498. /** @hidden */
  6499. KHR_materials_pbrSpecularGlossiness.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  6500. var _this = this;
  6501. return GLTF2.GLTFLoader.LoadExtensionAsync(context, material, this.name, function (extensionContext, extension) {
  6502. var promises = new Array();
  6503. promises.push(_this._loader.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  6504. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  6505. _this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);
  6506. return Promise.all(promises).then(function () { });
  6507. });
  6508. };
  6509. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  6510. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  6511. throw new Error(context + ": Material type not supported");
  6512. }
  6513. var promises = new Array();
  6514. babylonMaterial.metallic = null;
  6515. babylonMaterial.roughness = null;
  6516. if (properties.diffuseFactor) {
  6517. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  6518. babylonMaterial.alpha = properties.diffuseFactor[3];
  6519. }
  6520. else {
  6521. babylonMaterial.albedoColor = BABYLON.Color3.White();
  6522. }
  6523. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  6524. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  6525. if (properties.diffuseTexture) {
  6526. promises.push(this._loader.loadTextureInfoAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  6527. babylonMaterial.albedoTexture = texture;
  6528. return Promise.resolve();
  6529. }));
  6530. }
  6531. if (properties.specularGlossinessTexture) {
  6532. promises.push(this._loader.loadTextureInfoAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  6533. babylonMaterial.reflectivityTexture = texture;
  6534. return Promise.resolve();
  6535. }));
  6536. babylonMaterial.reflectivityTexture.hasAlpha = true;
  6537. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  6538. }
  6539. return Promise.all(promises).then(function () { });
  6540. };
  6541. return KHR_materials_pbrSpecularGlossiness;
  6542. }());
  6543. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  6544. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  6545. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  6546. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  6547. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  6548. })(BABYLON || (BABYLON = {}));
  6549. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  6550. var BABYLON;
  6551. (function (BABYLON) {
  6552. var GLTF2;
  6553. (function (GLTF2) {
  6554. var Loader;
  6555. (function (Loader) {
  6556. var Extensions;
  6557. (function (Extensions) {
  6558. var NAME = "KHR_materials_unlit";
  6559. /**
  6560. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  6561. */
  6562. var KHR_materials_unlit = /** @class */ (function () {
  6563. /** @hidden */
  6564. function KHR_materials_unlit(loader) {
  6565. /** The name of this extension. */
  6566. this.name = NAME;
  6567. /** Defines whether this extension is enabled. */
  6568. this.enabled = true;
  6569. this._loader = loader;
  6570. }
  6571. /** @hidden */
  6572. KHR_materials_unlit.prototype.dispose = function () {
  6573. delete this._loader;
  6574. };
  6575. /** @hidden */
  6576. KHR_materials_unlit.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  6577. var _this = this;
  6578. return GLTF2.GLTFLoader.LoadExtensionAsync(context, material, this.name, function () {
  6579. return _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  6580. });
  6581. };
  6582. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  6583. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  6584. throw new Error(context + ": Material type not supported");
  6585. }
  6586. var promises = new Array();
  6587. babylonMaterial.unlit = true;
  6588. var properties = material.pbrMetallicRoughness;
  6589. if (properties) {
  6590. if (properties.baseColorFactor) {
  6591. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  6592. babylonMaterial.alpha = properties.baseColorFactor[3];
  6593. }
  6594. else {
  6595. babylonMaterial.albedoColor = BABYLON.Color3.White();
  6596. }
  6597. if (properties.baseColorTexture) {
  6598. promises.push(this._loader.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  6599. babylonMaterial.albedoTexture = texture;
  6600. return Promise.resolve();
  6601. }));
  6602. }
  6603. }
  6604. if (material.doubleSided) {
  6605. babylonMaterial.backFaceCulling = false;
  6606. babylonMaterial.twoSidedLighting = true;
  6607. }
  6608. this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);
  6609. return Promise.all(promises).then(function () { });
  6610. };
  6611. return KHR_materials_unlit;
  6612. }());
  6613. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  6614. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  6615. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  6616. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  6617. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  6618. })(BABYLON || (BABYLON = {}));
  6619. //# sourceMappingURL=KHR_materials_unlit.js.map
  6620. var BABYLON;
  6621. (function (BABYLON) {
  6622. var GLTF2;
  6623. (function (GLTF2) {
  6624. var Loader;
  6625. (function (Loader) {
  6626. var Extensions;
  6627. (function (Extensions) {
  6628. var NAME = "KHR_lights_punctual";
  6629. var LightType;
  6630. (function (LightType) {
  6631. LightType["DIRECTIONAL"] = "directional";
  6632. LightType["POINT"] = "point";
  6633. LightType["SPOT"] = "spot";
  6634. })(LightType || (LightType = {}));
  6635. /**
  6636. * [Specification](https://github.com/KhronosGroup/glTF/blob/1048d162a44dbcb05aefc1874bfd423cf60135a6/extensions/2.0/Khronos/KHR_lights_punctual/README.md) (Experimental)
  6637. */
  6638. var KHR_lights = /** @class */ (function () {
  6639. /** @hidden */
  6640. function KHR_lights(loader) {
  6641. /** The name of this extension. */
  6642. this.name = NAME;
  6643. /** Defines whether this extension is enabled. */
  6644. this.enabled = true;
  6645. this._loader = loader;
  6646. }
  6647. /** @hidden */
  6648. KHR_lights.prototype.dispose = function () {
  6649. delete this._loader;
  6650. delete this._lights;
  6651. };
  6652. /** @hidden */
  6653. KHR_lights.prototype.onLoading = function () {
  6654. var extensions = this._loader.gltf.extensions;
  6655. if (extensions && extensions[this.name]) {
  6656. var extension = extensions[this.name];
  6657. this._lights = extension.lights;
  6658. }
  6659. };
  6660. /** @hidden */
  6661. KHR_lights.prototype.loadNodeAsync = function (context, node, assign) {
  6662. var _this = this;
  6663. return GLTF2.GLTFLoader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  6664. return _this._loader.loadNodeAsync(context, node, function (babylonMesh) {
  6665. var babylonLight;
  6666. var light = GLTF2.ArrayItem.Get(extensionContext, _this._lights, extension.light);
  6667. var name = light.name || babylonMesh.name;
  6668. switch (light.type) {
  6669. case LightType.DIRECTIONAL: {
  6670. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Backward(), _this._loader.babylonScene);
  6671. break;
  6672. }
  6673. case LightType.POINT: {
  6674. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader.babylonScene);
  6675. break;
  6676. }
  6677. case LightType.SPOT: {
  6678. var babylonSpotLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Backward(), 0, 1, _this._loader.babylonScene);
  6679. babylonSpotLight.angle = ((light.spot && light.spot.outerConeAngle) || Math.PI / 4) * 2;
  6680. babylonSpotLight.innerAngle = ((light.spot && light.spot.innerConeAngle) || 0) * 2;
  6681. babylonLight = babylonSpotLight;
  6682. break;
  6683. }
  6684. default: {
  6685. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  6686. }
  6687. }
  6688. babylonLight.falloffType = BABYLON.Light.FALLOFF_GLTF;
  6689. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  6690. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  6691. babylonLight.range = light.range == undefined ? Number.MAX_VALUE : light.range;
  6692. babylonLight.parent = babylonMesh;
  6693. assign(babylonMesh);
  6694. });
  6695. });
  6696. };
  6697. return KHR_lights;
  6698. }());
  6699. Extensions.KHR_lights = KHR_lights;
  6700. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_lights(loader); });
  6701. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  6702. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  6703. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  6704. })(BABYLON || (BABYLON = {}));
  6705. //# sourceMappingURL=KHR_lights_punctual.js.map
  6706. var BABYLON;
  6707. (function (BABYLON) {
  6708. var GLTF2;
  6709. (function (GLTF2) {
  6710. var Loader;
  6711. (function (Loader) {
  6712. var Extensions;
  6713. (function (Extensions) {
  6714. var NAME = "KHR_texture_transform";
  6715. /**
  6716. * [Specification](https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_texture_transform/README.md)
  6717. */
  6718. var KHR_texture_transform = /** @class */ (function () {
  6719. /** @hidden */
  6720. function KHR_texture_transform(loader) {
  6721. /** The name of this extension. */
  6722. this.name = NAME;
  6723. /** Defines whether this extension is enabled. */
  6724. this.enabled = true;
  6725. this._loader = loader;
  6726. }
  6727. /** @hidden */
  6728. KHR_texture_transform.prototype.dispose = function () {
  6729. delete this._loader;
  6730. };
  6731. /** @hidden */
  6732. KHR_texture_transform.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) {
  6733. var _this = this;
  6734. return GLTF2.GLTFLoader.LoadExtensionAsync(context, textureInfo, this.name, function (extensionContext, extension) {
  6735. return _this._loader.loadTextureInfoAsync(context, textureInfo, function (babylonTexture) {
  6736. if (!(babylonTexture instanceof BABYLON.Texture)) {
  6737. throw new Error(extensionContext + ": Texture type not supported");
  6738. }
  6739. if (extension.offset) {
  6740. babylonTexture.uOffset = extension.offset[0];
  6741. babylonTexture.vOffset = extension.offset[1];
  6742. }
  6743. // Always rotate around the origin.
  6744. babylonTexture.uRotationCenter = 0;
  6745. babylonTexture.vRotationCenter = 0;
  6746. if (extension.rotation) {
  6747. babylonTexture.wAng = -extension.rotation;
  6748. }
  6749. if (extension.scale) {
  6750. babylonTexture.uScale = extension.scale[0];
  6751. babylonTexture.vScale = extension.scale[1];
  6752. }
  6753. if (extension.texCoord != undefined) {
  6754. babylonTexture.coordinatesIndex = extension.texCoord;
  6755. }
  6756. assign(babylonTexture);
  6757. });
  6758. });
  6759. };
  6760. return KHR_texture_transform;
  6761. }());
  6762. Extensions.KHR_texture_transform = KHR_texture_transform;
  6763. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_texture_transform(loader); });
  6764. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  6765. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  6766. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  6767. })(BABYLON || (BABYLON = {}));
  6768. //# sourceMappingURL=KHR_texture_transform.js.map
  6769. var BABYLON;
  6770. (function (BABYLON) {
  6771. var GLTF2;
  6772. (function (GLTF2) {
  6773. var Loader;
  6774. (function (Loader) {
  6775. var Extensions;
  6776. (function (Extensions) {
  6777. var NAME = "EXT_lights_image_based";
  6778. /**
  6779. * [Specification](https://github.com/KhronosGroup/glTF/blob/eb3e32332042e04691a5f35103f8c261e50d8f1e/extensions/2.0/Khronos/EXT_lights_image_based/README.md) (Experimental)
  6780. */
  6781. var EXT_lights_image_based = /** @class */ (function () {
  6782. /** @hidden */
  6783. function EXT_lights_image_based(loader) {
  6784. /** The name of this extension. */
  6785. this.name = NAME;
  6786. /** Defines whether this extension is enabled. */
  6787. this.enabled = true;
  6788. this._loader = loader;
  6789. }
  6790. /** @hidden */
  6791. EXT_lights_image_based.prototype.dispose = function () {
  6792. delete this._loader;
  6793. delete this._lights;
  6794. };
  6795. /** @hidden */
  6796. EXT_lights_image_based.prototype.onLoading = function () {
  6797. var extensions = this._loader.gltf.extensions;
  6798. if (extensions && extensions[this.name]) {
  6799. var extension = extensions[this.name];
  6800. this._lights = extension.lights;
  6801. }
  6802. };
  6803. /** @hidden */
  6804. EXT_lights_image_based.prototype.loadSceneAsync = function (context, scene) {
  6805. var _this = this;
  6806. return GLTF2.GLTFLoader.LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) {
  6807. var promises = new Array();
  6808. promises.push(_this._loader.loadSceneAsync(context, scene));
  6809. _this._loader.logOpen("" + extensionContext);
  6810. var light = GLTF2.ArrayItem.Get(extensionContext + "/light", _this._lights, extension.light);
  6811. promises.push(_this._loadLightAsync("#/extensions/" + _this.name + "/lights/" + extension.light, light).then(function (texture) {
  6812. _this._loader.babylonScene.environmentTexture = texture;
  6813. }));
  6814. _this._loader.logClose();
  6815. return Promise.all(promises).then(function () { });
  6816. });
  6817. };
  6818. EXT_lights_image_based.prototype._loadLightAsync = function (context, light) {
  6819. var _this = this;
  6820. if (!light._loaded) {
  6821. var promises = new Array();
  6822. this._loader.logOpen("" + context);
  6823. var imageData_1 = new Array(light.specularImages.length);
  6824. var _loop_1 = function (mipmap) {
  6825. var faces = light.specularImages[mipmap];
  6826. imageData_1[mipmap] = new Array(faces.length);
  6827. var _loop_2 = function (face) {
  6828. var specularImageContext = context + "/specularImages/" + mipmap + "/" + face;
  6829. this_1._loader.logOpen("" + specularImageContext);
  6830. var index = faces[face];
  6831. var image = GLTF2.ArrayItem.Get(specularImageContext, this_1._loader.gltf.images, index);
  6832. promises.push(this_1._loader.loadImageAsync("#/images/" + index, image).then(function (data) {
  6833. imageData_1[mipmap][face] = data;
  6834. }));
  6835. this_1._loader.logClose();
  6836. };
  6837. for (var face = 0; face < faces.length; face++) {
  6838. _loop_2(face);
  6839. }
  6840. };
  6841. var this_1 = this;
  6842. for (var mipmap = 0; mipmap < light.specularImages.length; mipmap++) {
  6843. _loop_1(mipmap);
  6844. }
  6845. this._loader.logClose();
  6846. light._loaded = Promise.all(promises).then(function () {
  6847. var babylonTexture = new BABYLON.RawCubeTexture(_this._loader.babylonScene, null, light.specularImageSize);
  6848. light._babylonTexture = babylonTexture;
  6849. if (light.intensity != undefined) {
  6850. babylonTexture.level = light.intensity;
  6851. }
  6852. if (light.rotation) {
  6853. var rotation = BABYLON.Quaternion.FromArray(light.rotation);
  6854. // Invert the rotation so that positive rotation is counter-clockwise.
  6855. if (!_this._loader.babylonScene.useRightHandedSystem) {
  6856. rotation = BABYLON.Quaternion.Inverse(rotation);
  6857. }
  6858. BABYLON.Matrix.FromQuaternionToRef(rotation, babylonTexture.getReflectionTextureMatrix());
  6859. }
  6860. var sphericalHarmonics = BABYLON.SphericalHarmonics.FromArray(light.irradianceCoefficients);
  6861. sphericalHarmonics.scale(light.intensity);
  6862. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  6863. var sphericalPolynomial = BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  6864. // Compute the lod generation scale to fit exactly to the number of levels available.
  6865. var lodGenerationScale = (imageData_1.length - 1) / BABYLON.Scalar.Log2(light.specularImageSize);
  6866. return babylonTexture.updateRGBDAsync(imageData_1, sphericalPolynomial, lodGenerationScale);
  6867. });
  6868. }
  6869. return light._loaded.then(function () {
  6870. return light._babylonTexture;
  6871. });
  6872. };
  6873. return EXT_lights_image_based;
  6874. }());
  6875. Extensions.EXT_lights_image_based = EXT_lights_image_based;
  6876. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new EXT_lights_image_based(loader); });
  6877. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  6878. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  6879. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  6880. })(BABYLON || (BABYLON = {}));
  6881. //# sourceMappingURL=EXT_lights_image_based.js.map
  6882. return BABYLON;
  6883. });