babylonjs.loaders.js 359 KB

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