babylon.glTFFileLoader.js 307 KB

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