babylon.glTFFileLoader.js 307 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892
  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. var name_1 = getAttribute(attributeParameter);
  2043. if (name_1) {
  2044. attributes.push(name_1);
  2045. }
  2046. }
  2047. }
  2048. // Configure vertex shader
  2049. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  2050. var tokenType = vertexTokenizer.currentToken;
  2051. if (tokenType !== ETokenType.IDENTIFIER) {
  2052. newVertexShader += vertexTokenizer.currentString;
  2053. continue;
  2054. }
  2055. var foundAttribute = false;
  2056. for (var attr in technique.attributes) {
  2057. var attribute = technique.attributes[attr];
  2058. var attributeParameter = technique.parameters[attribute];
  2059. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  2060. newVertexShader += getAttribute(attributeParameter);
  2061. foundAttribute = true;
  2062. break;
  2063. }
  2064. }
  2065. if (foundAttribute) {
  2066. continue;
  2067. }
  2068. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  2069. }
  2070. // Configure pixel shader
  2071. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  2072. var tokenType = pixelTokenizer.currentToken;
  2073. if (tokenType !== ETokenType.IDENTIFIER) {
  2074. newPixelShader += pixelTokenizer.currentString;
  2075. continue;
  2076. }
  2077. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  2078. }
  2079. // Create shader material
  2080. var shaderPath = {
  2081. vertex: program.vertexShader + id,
  2082. fragment: program.fragmentShader + id
  2083. };
  2084. var options = {
  2085. attributes: attributes,
  2086. uniforms: uniforms,
  2087. samplers: samplers,
  2088. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  2089. };
  2090. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  2091. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  2092. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  2093. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  2094. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  2095. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2096. if (states && states.functions) {
  2097. var functions = states.functions;
  2098. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  2099. shaderMaterial.backFaceCulling = false;
  2100. }
  2101. var blendFunc = functions.blendFuncSeparate;
  2102. if (blendFunc) {
  2103. 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) {
  2104. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  2105. }
  2106. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2107. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  2108. }
  2109. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2110. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  2111. }
  2112. 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) {
  2113. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  2114. }
  2115. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2116. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  2117. }
  2118. 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) {
  2119. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  2120. }
  2121. }
  2122. }
  2123. };
  2124. return GLTFLoaderBase;
  2125. }());
  2126. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  2127. /**
  2128. * glTF V1 Loader
  2129. */
  2130. var GLTFLoader = /** @class */ (function () {
  2131. function GLTFLoader() {
  2132. this.state = null;
  2133. }
  2134. GLTFLoader.RegisterExtension = function (extension) {
  2135. if (GLTFLoader.Extensions[extension.name]) {
  2136. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  2137. return;
  2138. }
  2139. GLTFLoader.Extensions[extension.name] = extension;
  2140. };
  2141. GLTFLoader.prototype.dispose = function () {
  2142. // do nothing
  2143. };
  2144. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  2145. var _this = this;
  2146. scene.useRightHandedSystem = true;
  2147. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  2148. gltfRuntime.importOnlyMeshes = true;
  2149. if (meshesNames === "") {
  2150. gltfRuntime.importMeshesNames = [];
  2151. }
  2152. else if (typeof meshesNames === "string") {
  2153. gltfRuntime.importMeshesNames = [meshesNames];
  2154. }
  2155. else if (meshesNames && !(meshesNames instanceof Array)) {
  2156. gltfRuntime.importMeshesNames = [meshesNames];
  2157. }
  2158. else {
  2159. gltfRuntime.importMeshesNames = [];
  2160. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  2161. }
  2162. // Create nodes
  2163. _this._createNodes(gltfRuntime);
  2164. var meshes = new Array();
  2165. var skeletons = new Array();
  2166. // Fill arrays of meshes and skeletons
  2167. for (var nde in gltfRuntime.nodes) {
  2168. var node = gltfRuntime.nodes[nde];
  2169. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  2170. meshes.push(node.babylonNode);
  2171. }
  2172. }
  2173. for (var skl in gltfRuntime.skins) {
  2174. var skin = gltfRuntime.skins[skl];
  2175. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  2176. skeletons.push(skin.babylonSkeleton);
  2177. }
  2178. }
  2179. // Load buffers, shaders, materials, etc.
  2180. _this._loadBuffersAsync(gltfRuntime, function () {
  2181. _this._loadShadersAsync(gltfRuntime, function () {
  2182. importMaterials(gltfRuntime);
  2183. postLoad(gltfRuntime);
  2184. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  2185. onSuccess(meshes, skeletons);
  2186. }
  2187. });
  2188. }, onProgress);
  2189. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  2190. onSuccess(meshes, skeletons);
  2191. }
  2192. }, onError);
  2193. return true;
  2194. };
  2195. /**
  2196. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  2197. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  2198. * @param scene the scene the meshes should be added to
  2199. * @param data gltf data containing information of the meshes in a loaded file
  2200. * @param rootUrl root url to load from
  2201. * @param onProgress event that fires when loading progress has occured
  2202. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  2203. */
  2204. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  2205. var _this = this;
  2206. return new Promise(function (resolve, reject) {
  2207. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  2208. resolve({
  2209. meshes: meshes,
  2210. particleSystems: [],
  2211. skeletons: skeletons,
  2212. animationGroups: []
  2213. });
  2214. }, onProgress, function (message) {
  2215. reject(new Error(message));
  2216. });
  2217. });
  2218. };
  2219. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  2220. var _this = this;
  2221. scene.useRightHandedSystem = true;
  2222. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  2223. // Load runtime extensios
  2224. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  2225. // Create nodes
  2226. _this._createNodes(gltfRuntime);
  2227. // Load buffers, shaders, materials, etc.
  2228. _this._loadBuffersAsync(gltfRuntime, function () {
  2229. _this._loadShadersAsync(gltfRuntime, function () {
  2230. importMaterials(gltfRuntime);
  2231. postLoad(gltfRuntime);
  2232. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  2233. onSuccess();
  2234. }
  2235. });
  2236. });
  2237. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  2238. onSuccess();
  2239. }
  2240. }, onError);
  2241. }, onError);
  2242. };
  2243. /**
  2244. * Imports all objects from a loaded gltf file and adds them to the scene
  2245. * @param scene the scene the objects should be added to
  2246. * @param data gltf data containing information of the meshes in a loaded file
  2247. * @param rootUrl root url to load from
  2248. * @param onProgress event that fires when loading progress has occured
  2249. * @returns a promise which completes when objects have been loaded to the scene
  2250. */
  2251. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  2252. var _this = this;
  2253. return new Promise(function (resolve, reject) {
  2254. _this._loadAsync(scene, data, rootUrl, function () {
  2255. resolve();
  2256. }, onProgress, function (message) {
  2257. reject(new Error(message));
  2258. });
  2259. });
  2260. };
  2261. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  2262. var hasShaders = false;
  2263. var processShader = function (sha, shader) {
  2264. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  2265. if (shaderString instanceof ArrayBuffer) {
  2266. return;
  2267. }
  2268. gltfRuntime.loadedShaderCount++;
  2269. if (shaderString) {
  2270. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  2271. }
  2272. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  2273. onload();
  2274. }
  2275. }, function () {
  2276. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  2277. });
  2278. };
  2279. for (var sha in gltfRuntime.shaders) {
  2280. hasShaders = true;
  2281. var shader = gltfRuntime.shaders[sha];
  2282. if (shader) {
  2283. processShader.bind(this, sha, shader)();
  2284. }
  2285. else {
  2286. BABYLON.Tools.Error("No shader named: " + sha);
  2287. }
  2288. }
  2289. if (!hasShaders) {
  2290. onload();
  2291. }
  2292. };
  2293. ;
  2294. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  2295. var hasBuffers = false;
  2296. var processBuffer = function (buf, buffer) {
  2297. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  2298. gltfRuntime.loadedBufferCount++;
  2299. if (bufferView) {
  2300. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  2301. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  2302. }
  2303. gltfRuntime.loadedBufferViews[buf] = bufferView;
  2304. }
  2305. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  2306. onLoad();
  2307. }
  2308. }, function () {
  2309. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  2310. });
  2311. };
  2312. for (var buf in gltfRuntime.buffers) {
  2313. hasBuffers = true;
  2314. var buffer = gltfRuntime.buffers[buf];
  2315. if (buffer) {
  2316. processBuffer.bind(this, buf, buffer)();
  2317. }
  2318. else {
  2319. BABYLON.Tools.Error("No buffer named: " + buf);
  2320. }
  2321. }
  2322. if (!hasBuffers) {
  2323. onLoad();
  2324. }
  2325. };
  2326. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  2327. var currentScene = gltfRuntime.currentScene;
  2328. if (currentScene) {
  2329. // Only one scene even if multiple scenes are defined
  2330. for (var i = 0; i < currentScene.nodes.length; i++) {
  2331. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2332. }
  2333. }
  2334. else {
  2335. // Load all scenes
  2336. for (var thing in gltfRuntime.scenes) {
  2337. currentScene = gltfRuntime.scenes[thing];
  2338. for (var i = 0; i < currentScene.nodes.length; i++) {
  2339. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2340. }
  2341. }
  2342. }
  2343. };
  2344. GLTFLoader.Extensions = {};
  2345. return GLTFLoader;
  2346. }());
  2347. GLTF1.GLTFLoader = GLTFLoader;
  2348. ;
  2349. BABYLON.GLTFFileLoader._CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  2350. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2351. })(BABYLON || (BABYLON = {}));
  2352. //# sourceMappingURL=babylon.glTFLoader.js.map
  2353. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2354. var BABYLON;
  2355. (function (BABYLON) {
  2356. var GLTF1;
  2357. (function (GLTF1) {
  2358. /**
  2359. * Utils functions for GLTF
  2360. */
  2361. var GLTFUtils = /** @class */ (function () {
  2362. function GLTFUtils() {
  2363. }
  2364. /**
  2365. * Sets the given "parameter" matrix
  2366. * @param scene: the {BABYLON.Scene} object
  2367. * @param source: the source node where to pick the matrix
  2368. * @param parameter: the GLTF technique parameter
  2369. * @param uniformName: the name of the shader's uniform
  2370. * @param shaderMaterial: the shader material
  2371. */
  2372. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  2373. var mat = null;
  2374. if (parameter.semantic === "MODEL") {
  2375. mat = source.getWorldMatrix();
  2376. }
  2377. else if (parameter.semantic === "PROJECTION") {
  2378. mat = scene.getProjectionMatrix();
  2379. }
  2380. else if (parameter.semantic === "VIEW") {
  2381. mat = scene.getViewMatrix();
  2382. }
  2383. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  2384. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  2385. }
  2386. else if (parameter.semantic === "MODELVIEW") {
  2387. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  2388. }
  2389. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  2390. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  2391. }
  2392. else if (parameter.semantic === "MODELINVERSE") {
  2393. mat = source.getWorldMatrix().invert();
  2394. }
  2395. else if (parameter.semantic === "VIEWINVERSE") {
  2396. mat = scene.getViewMatrix().invert();
  2397. }
  2398. else if (parameter.semantic === "PROJECTIONINVERSE") {
  2399. mat = scene.getProjectionMatrix().invert();
  2400. }
  2401. else if (parameter.semantic === "MODELVIEWINVERSE") {
  2402. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  2403. }
  2404. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  2405. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  2406. }
  2407. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  2408. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  2409. }
  2410. else {
  2411. debugger;
  2412. }
  2413. if (mat) {
  2414. switch (parameter.type) {
  2415. case GLTF1.EParameterType.FLOAT_MAT2:
  2416. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  2417. break;
  2418. case GLTF1.EParameterType.FLOAT_MAT3:
  2419. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  2420. break;
  2421. case GLTF1.EParameterType.FLOAT_MAT4:
  2422. shaderMaterial.setMatrix(uniformName, mat);
  2423. break;
  2424. default: break;
  2425. }
  2426. }
  2427. };
  2428. /**
  2429. * Sets the given "parameter" matrix
  2430. * @param shaderMaterial: the shader material
  2431. * @param uniform: the name of the shader's uniform
  2432. * @param value: the value of the uniform
  2433. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  2434. */
  2435. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  2436. switch (type) {
  2437. case GLTF1.EParameterType.FLOAT:
  2438. shaderMaterial.setFloat(uniform, value);
  2439. return true;
  2440. case GLTF1.EParameterType.FLOAT_VEC2:
  2441. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  2442. return true;
  2443. case GLTF1.EParameterType.FLOAT_VEC3:
  2444. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  2445. return true;
  2446. case GLTF1.EParameterType.FLOAT_VEC4:
  2447. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  2448. return true;
  2449. default: return false;
  2450. }
  2451. };
  2452. /**
  2453. * Returns the wrap mode of the texture
  2454. * @param mode: the mode value
  2455. */
  2456. GLTFUtils.GetWrapMode = function (mode) {
  2457. switch (mode) {
  2458. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  2459. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  2460. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2461. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2462. }
  2463. };
  2464. /**
  2465. * Returns the byte stride giving an accessor
  2466. * @param accessor: the GLTF accessor objet
  2467. */
  2468. GLTFUtils.GetByteStrideFromType = function (accessor) {
  2469. // Needs this function since "byteStride" isn't requiered in glTF format
  2470. var type = accessor.type;
  2471. switch (type) {
  2472. case "VEC2": return 2;
  2473. case "VEC3": return 3;
  2474. case "VEC4": return 4;
  2475. case "MAT2": return 4;
  2476. case "MAT3": return 9;
  2477. case "MAT4": return 16;
  2478. default: return 1;
  2479. }
  2480. };
  2481. /**
  2482. * Returns the texture filter mode giving a mode value
  2483. * @param mode: the filter mode value
  2484. */
  2485. GLTFUtils.GetTextureFilterMode = function (mode) {
  2486. switch (mode) {
  2487. case GLTF1.ETextureFilterType.LINEAR:
  2488. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  2489. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  2490. case GLTF1.ETextureFilterType.NEAREST:
  2491. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  2492. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  2493. }
  2494. };
  2495. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  2496. var byteOffset = bufferView.byteOffset + byteOffset;
  2497. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  2498. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  2499. throw new Error("Buffer access is out of range");
  2500. }
  2501. var buffer = loadedBufferView.buffer;
  2502. byteOffset += loadedBufferView.byteOffset;
  2503. switch (componentType) {
  2504. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  2505. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  2506. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  2507. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  2508. default: return new Float32Array(buffer, byteOffset, byteLength);
  2509. }
  2510. };
  2511. /**
  2512. * Returns a buffer from its accessor
  2513. * @param gltfRuntime: the GLTF runtime
  2514. * @param accessor: the GLTF accessor
  2515. */
  2516. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  2517. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  2518. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  2519. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  2520. };
  2521. /**
  2522. * Decodes a buffer view into a string
  2523. * @param view: the buffer view
  2524. */
  2525. GLTFUtils.DecodeBufferToText = function (view) {
  2526. var result = "";
  2527. var length = view.byteLength;
  2528. for (var i = 0; i < length; ++i) {
  2529. result += String.fromCharCode(view[i]);
  2530. }
  2531. return result;
  2532. };
  2533. /**
  2534. * Returns the default material of gltf. Related to
  2535. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  2536. * @param scene: the Babylon.js scene
  2537. */
  2538. GLTFUtils.GetDefaultMaterial = function (scene) {
  2539. if (!GLTFUtils._DefaultMaterial) {
  2540. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  2541. "precision highp float;",
  2542. "",
  2543. "uniform mat4 worldView;",
  2544. "uniform mat4 projection;",
  2545. "",
  2546. "attribute vec3 position;",
  2547. "",
  2548. "void main(void)",
  2549. "{",
  2550. " gl_Position = projection * worldView * vec4(position, 1.0);",
  2551. "}"
  2552. ].join("\n");
  2553. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  2554. "precision highp float;",
  2555. "",
  2556. "uniform vec4 u_emission;",
  2557. "",
  2558. "void main(void)",
  2559. "{",
  2560. " gl_FragColor = u_emission;",
  2561. "}"
  2562. ].join("\n");
  2563. var shaderPath = {
  2564. vertex: "GLTFDefaultMaterial",
  2565. fragment: "GLTFDefaultMaterial"
  2566. };
  2567. var options = {
  2568. attributes: ["position"],
  2569. uniforms: ["worldView", "projection", "u_emission"],
  2570. samplers: new Array(),
  2571. needAlphaBlending: false
  2572. };
  2573. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  2574. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  2575. }
  2576. return GLTFUtils._DefaultMaterial;
  2577. };
  2578. // The GLTF default material
  2579. GLTFUtils._DefaultMaterial = null;
  2580. return GLTFUtils;
  2581. }());
  2582. GLTF1.GLTFUtils = GLTFUtils;
  2583. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2584. })(BABYLON || (BABYLON = {}));
  2585. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  2586. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2587. var BABYLON;
  2588. (function (BABYLON) {
  2589. var GLTF1;
  2590. (function (GLTF1) {
  2591. var GLTFLoaderExtension = /** @class */ (function () {
  2592. function GLTFLoaderExtension(name) {
  2593. this._name = name;
  2594. }
  2595. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  2596. get: function () {
  2597. return this._name;
  2598. },
  2599. enumerable: true,
  2600. configurable: true
  2601. });
  2602. /**
  2603. * Defines an override for loading the runtime
  2604. * Return true to stop further extensions from loading the runtime
  2605. */
  2606. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2607. return false;
  2608. };
  2609. /**
  2610. * Defines an onverride for creating gltf runtime
  2611. * Return true to stop further extensions from creating the runtime
  2612. */
  2613. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2614. return false;
  2615. };
  2616. /**
  2617. * Defines an override for loading buffers
  2618. * Return true to stop further extensions from loading this buffer
  2619. */
  2620. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2621. return false;
  2622. };
  2623. /**
  2624. * Defines an override for loading texture buffers
  2625. * Return true to stop further extensions from loading this texture data
  2626. */
  2627. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2628. return false;
  2629. };
  2630. /**
  2631. * Defines an override for creating textures
  2632. * Return true to stop further extensions from loading this texture
  2633. */
  2634. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2635. return false;
  2636. };
  2637. /**
  2638. * Defines an override for loading shader strings
  2639. * Return true to stop further extensions from loading this shader data
  2640. */
  2641. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2642. return false;
  2643. };
  2644. /**
  2645. * Defines an override for loading materials
  2646. * Return true to stop further extensions from loading this material
  2647. */
  2648. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2649. return false;
  2650. };
  2651. // ---------
  2652. // Utilities
  2653. // ---------
  2654. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2655. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2656. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  2657. }, function () {
  2658. setTimeout(function () {
  2659. if (!onSuccess) {
  2660. return;
  2661. }
  2662. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2663. });
  2664. });
  2665. };
  2666. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2667. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2668. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  2669. }, function () {
  2670. setTimeout(function () {
  2671. onSuccess();
  2672. });
  2673. });
  2674. };
  2675. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2676. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2677. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2678. }, function () {
  2679. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2680. });
  2681. };
  2682. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  2683. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2684. if (buffer) {
  2685. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2686. }
  2687. }, onError);
  2688. };
  2689. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2690. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2691. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2692. }, function () {
  2693. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2694. });
  2695. };
  2696. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2697. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2698. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2699. }, function () {
  2700. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2701. });
  2702. };
  2703. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2704. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2705. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2706. }, function () {
  2707. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2708. });
  2709. };
  2710. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2711. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2712. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2713. }, function () {
  2714. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2715. });
  2716. };
  2717. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  2718. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  2719. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  2720. if (func(loaderExtension)) {
  2721. return;
  2722. }
  2723. }
  2724. defaultFunc();
  2725. };
  2726. return GLTFLoaderExtension;
  2727. }());
  2728. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  2729. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2730. })(BABYLON || (BABYLON = {}));
  2731. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2732. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2733. var __extends = (this && this.__extends) || (function () {
  2734. var extendStatics = function (d, b) {
  2735. extendStatics = Object.setPrototypeOf ||
  2736. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2737. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2738. return extendStatics(d, b);
  2739. }
  2740. return function (d, b) {
  2741. extendStatics(d, b);
  2742. function __() { this.constructor = d; }
  2743. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2744. };
  2745. })();
  2746. var BABYLON;
  2747. (function (BABYLON) {
  2748. var GLTF1;
  2749. (function (GLTF1) {
  2750. var BinaryExtensionBufferName = "binary_glTF";
  2751. ;
  2752. ;
  2753. var GLTFBinaryExtension = /** @class */ (function (_super) {
  2754. __extends(GLTFBinaryExtension, _super);
  2755. function GLTFBinaryExtension() {
  2756. return _super.call(this, "KHR_binary_glTF") || this;
  2757. }
  2758. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2759. var extensionsUsed = data.json.extensionsUsed;
  2760. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  2761. return false;
  2762. }
  2763. this._bin = data.bin;
  2764. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2765. return true;
  2766. };
  2767. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2768. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  2769. return false;
  2770. }
  2771. if (id !== BinaryExtensionBufferName) {
  2772. return false;
  2773. }
  2774. onSuccess(this._bin);
  2775. return true;
  2776. };
  2777. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2778. var texture = gltfRuntime.textures[id];
  2779. var source = gltfRuntime.images[texture.source];
  2780. if (!source.extensions || !(this.name in source.extensions)) {
  2781. return false;
  2782. }
  2783. var sourceExt = source.extensions[this.name];
  2784. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  2785. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2786. onSuccess(buffer);
  2787. return true;
  2788. };
  2789. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2790. var shader = gltfRuntime.shaders[id];
  2791. if (!shader.extensions || !(this.name in shader.extensions)) {
  2792. return false;
  2793. }
  2794. var binaryExtensionShader = shader.extensions[this.name];
  2795. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  2796. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2797. setTimeout(function () {
  2798. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  2799. onSuccess(shaderString);
  2800. });
  2801. return true;
  2802. };
  2803. return GLTFBinaryExtension;
  2804. }(GLTF1.GLTFLoaderExtension));
  2805. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  2806. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  2807. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2808. })(BABYLON || (BABYLON = {}));
  2809. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  2810. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2811. var __extends = (this && this.__extends) || (function () {
  2812. var extendStatics = function (d, b) {
  2813. extendStatics = Object.setPrototypeOf ||
  2814. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2815. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2816. return extendStatics(d, b);
  2817. }
  2818. return function (d, b) {
  2819. extendStatics(d, b);
  2820. function __() { this.constructor = d; }
  2821. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2822. };
  2823. })();
  2824. var BABYLON;
  2825. (function (BABYLON) {
  2826. var GLTF1;
  2827. (function (GLTF1) {
  2828. ;
  2829. ;
  2830. ;
  2831. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  2832. __extends(GLTFMaterialsCommonExtension, _super);
  2833. function GLTFMaterialsCommonExtension() {
  2834. return _super.call(this, "KHR_materials_common") || this;
  2835. }
  2836. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2837. if (!gltfRuntime.extensions)
  2838. return false;
  2839. var extension = gltfRuntime.extensions[this.name];
  2840. if (!extension)
  2841. return false;
  2842. // Create lights
  2843. var lights = extension.lights;
  2844. if (lights) {
  2845. for (var thing in lights) {
  2846. var light = lights[thing];
  2847. switch (light.type) {
  2848. case "ambient":
  2849. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  2850. var ambient = light.ambient;
  2851. if (ambient) {
  2852. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  2853. }
  2854. break;
  2855. case "point":
  2856. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  2857. var point = light.point;
  2858. if (point) {
  2859. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  2860. }
  2861. break;
  2862. case "directional":
  2863. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  2864. var directional = light.directional;
  2865. if (directional) {
  2866. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  2867. }
  2868. break;
  2869. case "spot":
  2870. var spot = light.spot;
  2871. if (spot) {
  2872. 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);
  2873. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  2874. }
  2875. break;
  2876. default:
  2877. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  2878. break;
  2879. }
  2880. }
  2881. }
  2882. return false;
  2883. };
  2884. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2885. var material = gltfRuntime.materials[id];
  2886. if (!material || !material.extensions)
  2887. return false;
  2888. var extension = material.extensions[this.name];
  2889. if (!extension)
  2890. return false;
  2891. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2892. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2893. if (extension.technique === "CONSTANT") {
  2894. standardMaterial.disableLighting = true;
  2895. }
  2896. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2897. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2898. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2899. // Ambient
  2900. if (typeof extension.values.ambient === "string") {
  2901. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2902. }
  2903. else {
  2904. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2905. }
  2906. // Diffuse
  2907. if (typeof extension.values.diffuse === "string") {
  2908. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2909. }
  2910. else {
  2911. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2912. }
  2913. // Emission
  2914. if (typeof extension.values.emission === "string") {
  2915. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2916. }
  2917. else {
  2918. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2919. }
  2920. // Specular
  2921. if (typeof extension.values.specular === "string") {
  2922. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2923. }
  2924. else {
  2925. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2926. }
  2927. return true;
  2928. };
  2929. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2930. // Create buffer from texture url
  2931. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2932. // Create texture from buffer
  2933. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2934. }, onError);
  2935. };
  2936. return GLTFMaterialsCommonExtension;
  2937. }(GLTF1.GLTFLoaderExtension));
  2938. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  2939. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  2940. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2941. })(BABYLON || (BABYLON = {}));
  2942. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  2943. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2944. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  2945. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2946. /**
  2947. * Defines the module for importing and exporting glTF 2.0 assets
  2948. */
  2949. var BABYLON;
  2950. (function (BABYLON) {
  2951. var GLTF2;
  2952. (function (GLTF2) {
  2953. /**
  2954. * Helper class for working with arrays when loading the glTF asset
  2955. */
  2956. var ArrayItem = /** @class */ (function () {
  2957. function ArrayItem() {
  2958. }
  2959. /**
  2960. * Gets an item from the given array.
  2961. * @param context The context when loading the asset
  2962. * @param array The array to get the item from
  2963. * @param index The index to the array
  2964. * @returns The array item
  2965. */
  2966. ArrayItem.Get = function (context, array, index) {
  2967. if (!array || index == undefined || !array[index]) {
  2968. throw new Error(context + ": Failed to find index (" + index + ")");
  2969. }
  2970. return array[index];
  2971. };
  2972. /**
  2973. * Assign an `index` field to each item of the given array.
  2974. * @param array The array of items
  2975. */
  2976. ArrayItem.Assign = function (array) {
  2977. if (array) {
  2978. for (var index = 0; index < array.length; index++) {
  2979. array[index].index = index;
  2980. }
  2981. }
  2982. };
  2983. return ArrayItem;
  2984. }());
  2985. GLTF2.ArrayItem = ArrayItem;
  2986. /**
  2987. * The glTF 2.0 loader
  2988. */
  2989. var GLTFLoader = /** @class */ (function () {
  2990. /** @hidden */
  2991. function GLTFLoader(parent) {
  2992. /** @hidden */
  2993. this._completePromises = new Array();
  2994. this._disposed = false;
  2995. this._state = null;
  2996. this._extensions = {};
  2997. this._defaultBabylonMaterialData = {};
  2998. this._requests = new Array();
  2999. this._parent = parent;
  3000. }
  3001. /**
  3002. * Registers a loader extension.
  3003. * @param name The name of the loader extension.
  3004. * @param factory The factory function that creates the loader extension.
  3005. */
  3006. GLTFLoader.RegisterExtension = function (name, factory) {
  3007. if (GLTFLoader.UnregisterExtension(name)) {
  3008. BABYLON.Tools.Warn("Extension with the name '" + name + "' already exists");
  3009. }
  3010. GLTFLoader._ExtensionFactories[name] = factory;
  3011. // Keep the order of registration so that extensions registered first are called first.
  3012. GLTFLoader._ExtensionNames.push(name);
  3013. };
  3014. /**
  3015. * Unregisters a loader extension.
  3016. * @param name The name of the loader extenion.
  3017. * @returns A boolean indicating whether the extension has been unregistered
  3018. */
  3019. GLTFLoader.UnregisterExtension = function (name) {
  3020. if (!GLTFLoader._ExtensionFactories[name]) {
  3021. return false;
  3022. }
  3023. delete GLTFLoader._ExtensionFactories[name];
  3024. var index = GLTFLoader._ExtensionNames.indexOf(name);
  3025. if (index !== -1) {
  3026. GLTFLoader._ExtensionNames.splice(index, 1);
  3027. }
  3028. return true;
  3029. };
  3030. Object.defineProperty(GLTFLoader.prototype, "state", {
  3031. /**
  3032. * Gets the loader state.
  3033. */
  3034. get: function () {
  3035. return this._state;
  3036. },
  3037. enumerable: true,
  3038. configurable: true
  3039. });
  3040. /** @hidden */
  3041. GLTFLoader.prototype.dispose = function () {
  3042. if (this._disposed) {
  3043. return;
  3044. }
  3045. this._disposed = true;
  3046. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  3047. var request = _a[_i];
  3048. request.abort();
  3049. }
  3050. this._requests.length = 0;
  3051. delete this.gltf;
  3052. delete this.babylonScene;
  3053. this._completePromises.length = 0;
  3054. for (var name_1 in this._extensions) {
  3055. var extension = this._extensions[name_1];
  3056. if (extension.dispose) {
  3057. this._extensions[name_1].dispose();
  3058. }
  3059. }
  3060. this._extensions = {};
  3061. delete this._rootBabylonMesh;
  3062. delete this._progressCallback;
  3063. this._parent._clear();
  3064. };
  3065. /** @hidden */
  3066. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  3067. var _this = this;
  3068. return Promise.resolve().then(function () {
  3069. _this.babylonScene = scene;
  3070. _this._rootUrl = rootUrl;
  3071. _this._fileName = fileName || "scene";
  3072. _this._progressCallback = onProgress;
  3073. _this._loadData(data);
  3074. var nodes = null;
  3075. if (meshesNames) {
  3076. var nodeMap_1 = {};
  3077. if (_this.gltf.nodes) {
  3078. for (var _i = 0, _a = _this.gltf.nodes; _i < _a.length; _i++) {
  3079. var node = _a[_i];
  3080. if (node.name) {
  3081. nodeMap_1[node.name] = node.index;
  3082. }
  3083. }
  3084. }
  3085. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  3086. nodes = names.map(function (name) {
  3087. var node = nodeMap_1[name];
  3088. if (node === undefined) {
  3089. throw new Error("Failed to find node '" + name + "'");
  3090. }
  3091. return node;
  3092. });
  3093. }
  3094. return _this._loadAsync(nodes, function () {
  3095. return {
  3096. meshes: _this._getMeshes(),
  3097. particleSystems: [],
  3098. skeletons: _this._getSkeletons(),
  3099. animationGroups: _this._getAnimationGroups()
  3100. };
  3101. });
  3102. });
  3103. };
  3104. /** @hidden */
  3105. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  3106. var _this = this;
  3107. return Promise.resolve().then(function () {
  3108. _this.babylonScene = scene;
  3109. _this._rootUrl = rootUrl;
  3110. _this._fileName = fileName || "scene";
  3111. _this._progressCallback = onProgress;
  3112. _this._loadData(data);
  3113. return _this._loadAsync(null, function () { return undefined; });
  3114. });
  3115. };
  3116. GLTFLoader.prototype._loadAsync = function (nodes, resultFunc) {
  3117. var _this = this;
  3118. return Promise.resolve().then(function () {
  3119. _this._uniqueRootUrl = (_this._rootUrl.indexOf("file:") === -1 && _this._fileName) ? _this._rootUrl : "" + _this._rootUrl + Date.now() + "/";
  3120. _this._loadExtensions();
  3121. _this._checkExtensions();
  3122. var loadingToReadyCounterName = BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.LOADING] + " => " + BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.READY];
  3123. var loadingToCompleteCounterName = BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.LOADING] + " => " + BABYLON.GLTFLoaderState[BABYLON.GLTFLoaderState.COMPLETE];
  3124. _this._parent._startPerformanceCounter(loadingToReadyCounterName);
  3125. _this._parent._startPerformanceCounter(loadingToCompleteCounterName);
  3126. _this._setState(BABYLON.GLTFLoaderState.LOADING);
  3127. _this._extensionsOnLoading();
  3128. var promises = new Array();
  3129. if (nodes) {
  3130. promises.push(_this.loadSceneAsync("#/nodes", { nodes: nodes, index: -1 }));
  3131. }
  3132. else {
  3133. var scene = ArrayItem.Get("#/scene", _this.gltf.scenes, _this.gltf.scene || 0);
  3134. promises.push(_this.loadSceneAsync("#/scenes/" + scene.index, scene));
  3135. }
  3136. if (_this._parent.compileMaterials) {
  3137. promises.push(_this._compileMaterialsAsync());
  3138. }
  3139. if (_this._parent.compileShadowGenerators) {
  3140. promises.push(_this._compileShadowGeneratorsAsync());
  3141. }
  3142. var resultPromise = Promise.all(promises).then(function () {
  3143. _this._setState(BABYLON.GLTFLoaderState.READY);
  3144. _this._extensionsOnReady();
  3145. _this._startAnimations();
  3146. return resultFunc();
  3147. });
  3148. resultPromise.then(function () {
  3149. _this._parent._endPerformanceCounter(loadingToReadyCounterName);
  3150. BABYLON.Tools.SetImmediate(function () {
  3151. if (!_this._disposed) {
  3152. Promise.all(_this._completePromises).then(function () {
  3153. _this._parent._endPerformanceCounter(loadingToCompleteCounterName);
  3154. _this._setState(BABYLON.GLTFLoaderState.COMPLETE);
  3155. _this._parent.onCompleteObservable.notifyObservers(undefined);
  3156. _this._parent.onCompleteObservable.clear();
  3157. _this.dispose();
  3158. }, function (error) {
  3159. _this._parent.onErrorObservable.notifyObservers(error);
  3160. _this._parent.onErrorObservable.clear();
  3161. _this.dispose();
  3162. });
  3163. }
  3164. });
  3165. });
  3166. return resultPromise;
  3167. }, function (error) {
  3168. if (!_this._disposed) {
  3169. _this._parent.onErrorObservable.notifyObservers(error);
  3170. _this._parent.onErrorObservable.clear();
  3171. _this.dispose();
  3172. }
  3173. throw error;
  3174. });
  3175. };
  3176. GLTFLoader.prototype._loadData = function (data) {
  3177. this.gltf = data.json;
  3178. this._setupData();
  3179. if (data.bin) {
  3180. var buffers = this.gltf.buffers;
  3181. if (buffers && buffers[0] && !buffers[0].uri) {
  3182. var binaryBuffer = buffers[0];
  3183. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  3184. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  3185. }
  3186. binaryBuffer._data = Promise.resolve(data.bin);
  3187. }
  3188. else {
  3189. BABYLON.Tools.Warn("Unexpected BIN chunk");
  3190. }
  3191. }
  3192. };
  3193. GLTFLoader.prototype._setupData = function () {
  3194. ArrayItem.Assign(this.gltf.accessors);
  3195. ArrayItem.Assign(this.gltf.animations);
  3196. ArrayItem.Assign(this.gltf.buffers);
  3197. ArrayItem.Assign(this.gltf.bufferViews);
  3198. ArrayItem.Assign(this.gltf.cameras);
  3199. ArrayItem.Assign(this.gltf.images);
  3200. ArrayItem.Assign(this.gltf.materials);
  3201. ArrayItem.Assign(this.gltf.meshes);
  3202. ArrayItem.Assign(this.gltf.nodes);
  3203. ArrayItem.Assign(this.gltf.samplers);
  3204. ArrayItem.Assign(this.gltf.scenes);
  3205. ArrayItem.Assign(this.gltf.skins);
  3206. ArrayItem.Assign(this.gltf.textures);
  3207. if (this.gltf.nodes) {
  3208. var nodeParents = {};
  3209. for (var _i = 0, _a = this.gltf.nodes; _i < _a.length; _i++) {
  3210. var node = _a[_i];
  3211. if (node.children) {
  3212. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  3213. var index = _c[_b];
  3214. nodeParents[index] = node.index;
  3215. }
  3216. }
  3217. }
  3218. var rootNode = this._createRootNode();
  3219. for (var _d = 0, _e = this.gltf.nodes; _d < _e.length; _d++) {
  3220. var node = _e[_d];
  3221. var parentIndex = nodeParents[node.index];
  3222. node.parent = parentIndex === undefined ? rootNode : this.gltf.nodes[parentIndex];
  3223. }
  3224. }
  3225. };
  3226. GLTFLoader.prototype._loadExtensions = function () {
  3227. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  3228. var name_2 = _a[_i];
  3229. var extension = GLTFLoader._ExtensionFactories[name_2](this);
  3230. this._extensions[name_2] = extension;
  3231. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  3232. }
  3233. this._parent.onExtensionLoadedObservable.clear();
  3234. };
  3235. GLTFLoader.prototype._checkExtensions = function () {
  3236. if (this.gltf.extensionsRequired) {
  3237. for (var _i = 0, _a = this.gltf.extensionsRequired; _i < _a.length; _i++) {
  3238. var name_3 = _a[_i];
  3239. var extension = this._extensions[name_3];
  3240. if (!extension || !extension.enabled) {
  3241. throw new Error("Require extension " + name_3 + " is not available");
  3242. }
  3243. }
  3244. }
  3245. };
  3246. GLTFLoader.prototype._setState = function (state) {
  3247. this._state = state;
  3248. this.log(BABYLON.GLTFLoaderState[this._state]);
  3249. };
  3250. GLTFLoader.prototype._createRootNode = function () {
  3251. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this.babylonScene);
  3252. var rootNode = {
  3253. _babylonMesh: this._rootBabylonMesh,
  3254. index: -1
  3255. };
  3256. switch (this._parent.coordinateSystemMode) {
  3257. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  3258. if (!this.babylonScene.useRightHandedSystem) {
  3259. rootNode.rotation = [0, 1, 0, 0];
  3260. rootNode.scale = [1, 1, -1];
  3261. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  3262. }
  3263. break;
  3264. }
  3265. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  3266. this.babylonScene.useRightHandedSystem = true;
  3267. break;
  3268. }
  3269. default: {
  3270. throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  3271. }
  3272. }
  3273. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  3274. return rootNode;
  3275. };
  3276. /**
  3277. * Loads a glTF scene.
  3278. * @param context The context when loading the asset
  3279. * @param scene The glTF scene property
  3280. * @returns A promise that resolves when the load is complete
  3281. */
  3282. GLTFLoader.prototype.loadSceneAsync = function (context, scene) {
  3283. var _this = this;
  3284. var extensionPromise = this._extensionsLoadSceneAsync(context, scene);
  3285. if (extensionPromise) {
  3286. return extensionPromise;
  3287. }
  3288. var promises = new Array();
  3289. this.logOpen(context + " " + (scene.name || ""));
  3290. if (scene.nodes) {
  3291. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  3292. var index = _a[_i];
  3293. var node = ArrayItem.Get(context + "/nodes/" + index, this.gltf.nodes, index);
  3294. promises.push(this.loadNodeAsync("#/nodes/" + node.index, node, function (babylonMesh) {
  3295. babylonMesh.parent = _this._rootBabylonMesh;
  3296. }));
  3297. }
  3298. }
  3299. promises.push(this._loadAnimationsAsync());
  3300. this.logClose();
  3301. return Promise.all(promises).then(function () { });
  3302. };
  3303. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  3304. if (node._primitiveBabylonMeshes) {
  3305. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  3306. var babylonMesh = _a[_i];
  3307. callback(babylonMesh);
  3308. }
  3309. }
  3310. else {
  3311. callback(node._babylonMesh);
  3312. }
  3313. };
  3314. GLTFLoader.prototype._getMeshes = function () {
  3315. var meshes = new Array();
  3316. // Root mesh is always first.
  3317. meshes.push(this._rootBabylonMesh);
  3318. var nodes = this.gltf.nodes;
  3319. if (nodes) {
  3320. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  3321. var node = nodes_1[_i];
  3322. if (node._babylonMesh) {
  3323. meshes.push(node._babylonMesh);
  3324. }
  3325. if (node._primitiveBabylonMeshes) {
  3326. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  3327. var babylonMesh = _b[_a];
  3328. meshes.push(babylonMesh);
  3329. }
  3330. }
  3331. }
  3332. }
  3333. return meshes;
  3334. };
  3335. GLTFLoader.prototype._getSkeletons = function () {
  3336. var skeletons = new Array();
  3337. var skins = this.gltf.skins;
  3338. if (skins) {
  3339. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  3340. var skin = skins_1[_i];
  3341. if (skin._babylonSkeleton) {
  3342. skeletons.push(skin._babylonSkeleton);
  3343. }
  3344. }
  3345. }
  3346. return skeletons;
  3347. };
  3348. GLTFLoader.prototype._getAnimationGroups = function () {
  3349. var animationGroups = new Array();
  3350. var animations = this.gltf.animations;
  3351. if (animations) {
  3352. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  3353. var animation = animations_1[_i];
  3354. if (animation._babylonAnimationGroup) {
  3355. animationGroups.push(animation._babylonAnimationGroup);
  3356. }
  3357. }
  3358. }
  3359. return animationGroups;
  3360. };
  3361. GLTFLoader.prototype._startAnimations = function () {
  3362. switch (this._parent.animationStartMode) {
  3363. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  3364. // do nothing
  3365. break;
  3366. }
  3367. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  3368. var babylonAnimationGroups = this._getAnimationGroups();
  3369. if (babylonAnimationGroups.length !== 0) {
  3370. babylonAnimationGroups[0].start(true);
  3371. }
  3372. break;
  3373. }
  3374. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  3375. var babylonAnimationGroups = this._getAnimationGroups();
  3376. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  3377. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  3378. babylonAnimationGroup.start(true);
  3379. }
  3380. break;
  3381. }
  3382. default: {
  3383. BABYLON.Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
  3384. return;
  3385. }
  3386. }
  3387. };
  3388. /**
  3389. * Loads a glTF node.
  3390. * @param context The context when loading the asset
  3391. * @param node The glTF node property
  3392. * @param assign A function called synchronously after parsing the glTF properties
  3393. * @returns A promise that resolves with the loaded Babylon mesh when the load is complete
  3394. */
  3395. GLTFLoader.prototype.loadNodeAsync = function (context, node, assign) {
  3396. var _this = this;
  3397. if (assign === void 0) { assign = function () { }; }
  3398. var extensionPromise = this._extensionsLoadNodeAsync(context, node, assign);
  3399. if (extensionPromise) {
  3400. return extensionPromise;
  3401. }
  3402. if (node._babylonMesh) {
  3403. throw new Error(context + ": Invalid recursive node hierarchy");
  3404. }
  3405. var promises = new Array();
  3406. this.logOpen(context + " " + (node.name || ""));
  3407. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node.index, this.babylonScene);
  3408. node._babylonMesh = babylonMesh;
  3409. babylonMesh.setEnabled(false);
  3410. GLTFLoader._LoadTransform(node, babylonMesh);
  3411. if (node.mesh != undefined) {
  3412. var mesh = ArrayItem.Get(context + "/mesh", this.gltf.meshes, node.mesh);
  3413. promises.push(this._loadMeshAsync("#/meshes/" + mesh.index, node, mesh, babylonMesh));
  3414. }
  3415. if (node.camera != undefined) {
  3416. var camera = ArrayItem.Get(context + "/camera", this.gltf.cameras, node.camera);
  3417. promises.push(this.loadCameraAsync("#/cameras/" + camera.index, camera, function (babylonCamera) {
  3418. babylonCamera.parent = babylonMesh;
  3419. }));
  3420. }
  3421. if (node.children) {
  3422. var _loop_1 = function (index) {
  3423. var childNode = ArrayItem.Get(context + "/children/" + index, this_1.gltf.nodes, index);
  3424. promises.push(this_1.loadNodeAsync("#/nodes/" + node.index, childNode, function (childBabylonMesh) {
  3425. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  3426. if (childNode.skin != undefined) {
  3427. childBabylonMesh.parent = _this._rootBabylonMesh;
  3428. return;
  3429. }
  3430. childBabylonMesh.parent = babylonMesh;
  3431. }));
  3432. };
  3433. var this_1 = this;
  3434. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  3435. var index = _a[_i];
  3436. _loop_1(index);
  3437. }
  3438. }
  3439. assign(babylonMesh);
  3440. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  3441. this.logClose();
  3442. return Promise.all(promises).then(function () {
  3443. babylonMesh.setEnabled(true);
  3444. return babylonMesh;
  3445. });
  3446. };
  3447. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  3448. var _this = this;
  3449. var promises = new Array();
  3450. this.logOpen(context + " " + (mesh.name || ""));
  3451. var primitives = mesh.primitives;
  3452. if (!primitives || primitives.length === 0) {
  3453. throw new Error(context + ": Primitives are missing");
  3454. }
  3455. ArrayItem.Assign(primitives);
  3456. if (primitives.length === 1) {
  3457. var primitive = primitives[0];
  3458. promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, node, mesh, primitive, babylonMesh));
  3459. }
  3460. else {
  3461. node._primitiveBabylonMeshes = [];
  3462. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  3463. var primitive = primitives_1[_i];
  3464. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive.index, this.babylonScene, babylonMesh);
  3465. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  3466. promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, node, mesh, primitive, primitiveBabylonMesh));
  3467. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  3468. }
  3469. }
  3470. if (node.skin != undefined) {
  3471. var skin = ArrayItem.Get(context + "/skin", this.gltf.skins, node.skin);
  3472. promises.push(this._loadSkinAsync("#/skins/" + skin.index, node, skin));
  3473. }
  3474. this.logClose();
  3475. return Promise.all(promises).then(function () {
  3476. _this._forEachPrimitive(node, function (babylonMesh) {
  3477. babylonMesh._refreshBoundingInfo(true);
  3478. });
  3479. });
  3480. };
  3481. GLTFLoader.prototype._loadMeshPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  3482. var _this = this;
  3483. var promises = new Array();
  3484. this.logOpen("" + context);
  3485. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  3486. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  3487. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  3488. babylonGeometry.applyToMesh(babylonMesh);
  3489. });
  3490. }));
  3491. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  3492. if (primitive.material == undefined) {
  3493. var babylonMaterial = this._defaultBabylonMaterialData[babylonDrawMode];
  3494. if (!babylonMaterial) {
  3495. babylonMaterial = this._createDefaultMaterial("__gltf_default", babylonDrawMode);
  3496. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  3497. this._defaultBabylonMaterialData[babylonDrawMode] = babylonMaterial;
  3498. }
  3499. babylonMesh.material = babylonMaterial;
  3500. }
  3501. else {
  3502. var material = ArrayItem.Get(context + "/material", this.gltf.materials, primitive.material);
  3503. promises.push(this._loadMaterialAsync("#/materials/" + material.index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  3504. babylonMesh.material = babylonMaterial;
  3505. }));
  3506. }
  3507. this.logClose();
  3508. return Promise.all(promises).then(function () { });
  3509. };
  3510. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  3511. var _this = this;
  3512. var extensionPromise = this._extensionsLoadVertexDataAsync(context, primitive, babylonMesh);
  3513. if (extensionPromise) {
  3514. return extensionPromise;
  3515. }
  3516. var attributes = primitive.attributes;
  3517. if (!attributes) {
  3518. throw new Error(context + ": Attributes are missing");
  3519. }
  3520. var promises = new Array();
  3521. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this.babylonScene);
  3522. if (primitive.indices == undefined) {
  3523. babylonMesh.isUnIndexed = true;
  3524. }
  3525. else {
  3526. var accessor = ArrayItem.Get(context + "/indices", this.gltf.accessors, primitive.indices);
  3527. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  3528. babylonGeometry.setIndices(data);
  3529. }));
  3530. }
  3531. var loadAttribute = function (attribute, kind, callback) {
  3532. if (attributes[attribute] == undefined) {
  3533. return;
  3534. }
  3535. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  3536. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  3537. babylonMesh._delayInfo.push(kind);
  3538. }
  3539. var accessor = ArrayItem.Get(context + "/attributes/" + attribute, _this.gltf.accessors, attributes[attribute]);
  3540. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor.index, accessor, kind).then(function (babylonVertexBuffer) {
  3541. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  3542. }));
  3543. if (callback) {
  3544. callback(accessor);
  3545. }
  3546. };
  3547. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  3548. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  3549. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  3550. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  3551. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  3552. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  3553. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  3554. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  3555. if (accessor.type === "VEC4" /* VEC4 */) {
  3556. babylonMesh.hasVertexAlpha = true;
  3557. }
  3558. });
  3559. return Promise.all(promises).then(function () {
  3560. return babylonGeometry;
  3561. });
  3562. };
  3563. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  3564. if (!primitive.targets) {
  3565. return;
  3566. }
  3567. if (node._numMorphTargets == undefined) {
  3568. node._numMorphTargets = primitive.targets.length;
  3569. }
  3570. else if (primitive.targets.length !== node._numMorphTargets) {
  3571. throw new Error(context + ": Primitives do not have the same number of targets");
  3572. }
  3573. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  3574. for (var index = 0; index < primitive.targets.length; index++) {
  3575. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  3576. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  3577. // TODO: tell the target whether it has positions, normals, tangents
  3578. }
  3579. };
  3580. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  3581. if (!primitive.targets) {
  3582. return Promise.resolve();
  3583. }
  3584. var promises = new Array();
  3585. var morphTargetManager = babylonMesh.morphTargetManager;
  3586. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  3587. var babylonMorphTarget = morphTargetManager.getTarget(index);
  3588. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  3589. }
  3590. return Promise.all(promises).then(function () { });
  3591. };
  3592. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  3593. var _this = this;
  3594. var promises = new Array();
  3595. var loadAttribute = function (attribute, kind, setData) {
  3596. if (attributes[attribute] == undefined) {
  3597. return;
  3598. }
  3599. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  3600. if (!babylonVertexBuffer) {
  3601. return;
  3602. }
  3603. var accessor = ArrayItem.Get(context + "/" + attribute, _this.gltf.accessors, attributes[attribute]);
  3604. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  3605. setData(babylonVertexBuffer, data);
  3606. }));
  3607. };
  3608. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  3609. babylonVertexBuffer.forEach(data.length, function (value, index) {
  3610. data[index] += value;
  3611. });
  3612. babylonMorphTarget.setPositions(data);
  3613. });
  3614. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  3615. babylonVertexBuffer.forEach(data.length, function (value, index) {
  3616. data[index] += value;
  3617. });
  3618. babylonMorphTarget.setNormals(data);
  3619. });
  3620. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  3621. var dataIndex = 0;
  3622. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  3623. // Tangent data for morph targets is stored as xyz delta.
  3624. // The vertexData.tangent is stored as xyzw.
  3625. // So we need to skip every fourth vertexData.tangent.
  3626. if (((index + 1) % 4) !== 0) {
  3627. data[dataIndex++] += value;
  3628. }
  3629. });
  3630. babylonMorphTarget.setTangents(data);
  3631. });
  3632. return Promise.all(promises).then(function () { });
  3633. };
  3634. GLTFLoader._LoadTransform = function (node, babylonNode) {
  3635. var position = BABYLON.Vector3.Zero();
  3636. var rotation = BABYLON.Quaternion.Identity();
  3637. var scaling = BABYLON.Vector3.One();
  3638. if (node.matrix) {
  3639. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  3640. matrix.decompose(scaling, rotation, position);
  3641. }
  3642. else {
  3643. if (node.translation)
  3644. position = BABYLON.Vector3.FromArray(node.translation);
  3645. if (node.rotation)
  3646. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  3647. if (node.scale)
  3648. scaling = BABYLON.Vector3.FromArray(node.scale);
  3649. }
  3650. babylonNode.position = position;
  3651. babylonNode.rotationQuaternion = rotation;
  3652. babylonNode.scaling = scaling;
  3653. };
  3654. GLTFLoader.prototype._loadSkinAsync = function (context, node, skin) {
  3655. var _this = this;
  3656. var assignSkeleton = function (skeleton) {
  3657. _this._forEachPrimitive(node, function (babylonMesh) {
  3658. babylonMesh.skeleton = skeleton;
  3659. });
  3660. // Ignore the TRS of skinned nodes.
  3661. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  3662. node._babylonMesh.position = BABYLON.Vector3.Zero();
  3663. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  3664. node._babylonMesh.scaling = BABYLON.Vector3.One();
  3665. };
  3666. if (skin._promise) {
  3667. return skin._promise.then(function () {
  3668. assignSkeleton(skin._babylonSkeleton);
  3669. });
  3670. }
  3671. var skeletonId = "skeleton" + skin.index;
  3672. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this.babylonScene);
  3673. skin._babylonSkeleton = babylonSkeleton;
  3674. this._loadBones(context, skin);
  3675. assignSkeleton(babylonSkeleton);
  3676. return (skin._promise = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  3677. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  3678. }));
  3679. };
  3680. GLTFLoader.prototype._loadBones = function (context, skin) {
  3681. var babylonBones = {};
  3682. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  3683. var index = _a[_i];
  3684. var node = ArrayItem.Get(context + "/joints/" + index, this.gltf.nodes, index);
  3685. this._loadBone(node, skin, babylonBones);
  3686. }
  3687. };
  3688. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  3689. var babylonBone = babylonBones[node.index];
  3690. if (babylonBone) {
  3691. return babylonBone;
  3692. }
  3693. var babylonParentBone = null;
  3694. if (node.parent && node.parent._babylonMesh !== this._rootBabylonMesh) {
  3695. babylonParentBone = this._loadBone(node.parent, skin, babylonBones);
  3696. }
  3697. var boneIndex = skin.joints.indexOf(node.index);
  3698. babylonBone = new BABYLON.Bone(node.name || "joint" + node.index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  3699. babylonBones[node.index] = babylonBone;
  3700. node._babylonBones = node._babylonBones || [];
  3701. node._babylonBones.push(babylonBone);
  3702. return babylonBone;
  3703. };
  3704. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  3705. if (skin.inverseBindMatrices == undefined) {
  3706. return Promise.resolve(null);
  3707. }
  3708. var accessor = ArrayItem.Get(context + "/inverseBindMatrices", this.gltf.accessors, skin.inverseBindMatrices);
  3709. return this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor);
  3710. };
  3711. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  3712. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  3713. var babylonBone = _a[_i];
  3714. var baseMatrix = BABYLON.Matrix.Identity();
  3715. var boneIndex = babylonBone._index;
  3716. if (inverseBindMatricesData && boneIndex !== -1) {
  3717. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  3718. baseMatrix.invertToRef(baseMatrix);
  3719. }
  3720. var babylonParentBone = babylonBone.getParent();
  3721. if (babylonParentBone) {
  3722. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  3723. }
  3724. babylonBone.updateMatrix(baseMatrix, false, false);
  3725. babylonBone._updateDifferenceMatrix(undefined, false);
  3726. }
  3727. };
  3728. GLTFLoader.prototype._getNodeMatrix = function (node) {
  3729. return node.matrix ?
  3730. BABYLON.Matrix.FromArray(node.matrix) :
  3731. 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());
  3732. };
  3733. /**
  3734. * Loads a glTF camera.
  3735. * @param context The context when loading the asset
  3736. * @param camera The glTF camera property
  3737. * @param assign A function called synchronously after parsing the glTF properties
  3738. * @returns A promise that resolves with the loaded Babylon camera when the load is complete
  3739. */
  3740. GLTFLoader.prototype.loadCameraAsync = function (context, camera, assign) {
  3741. if (assign === void 0) { assign = function () { }; }
  3742. var extensionPromise = this._extensionsLoadCameraAsync(context, camera, assign);
  3743. if (extensionPromise) {
  3744. return extensionPromise;
  3745. }
  3746. var promises = new Array();
  3747. this.logOpen(context + " " + (camera.name || ""));
  3748. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera.index, BABYLON.Vector3.Zero(), this.babylonScene, false);
  3749. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  3750. switch (camera.type) {
  3751. case "perspective" /* PERSPECTIVE */: {
  3752. var perspective = camera.perspective;
  3753. if (!perspective) {
  3754. throw new Error(context + ": Camera perspective properties are missing");
  3755. }
  3756. babylonCamera.fov = perspective.yfov;
  3757. babylonCamera.minZ = perspective.znear;
  3758. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  3759. break;
  3760. }
  3761. case "orthographic" /* ORTHOGRAPHIC */: {
  3762. if (!camera.orthographic) {
  3763. throw new Error(context + ": Camera orthographic properties are missing");
  3764. }
  3765. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  3766. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  3767. babylonCamera.orthoRight = camera.orthographic.xmag;
  3768. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  3769. babylonCamera.orthoTop = camera.orthographic.ymag;
  3770. babylonCamera.minZ = camera.orthographic.znear;
  3771. babylonCamera.maxZ = camera.orthographic.zfar;
  3772. break;
  3773. }
  3774. default: {
  3775. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  3776. }
  3777. }
  3778. assign(babylonCamera);
  3779. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  3780. return Promise.all(promises).then(function () {
  3781. return babylonCamera;
  3782. });
  3783. };
  3784. GLTFLoader.prototype._loadAnimationsAsync = function () {
  3785. var animations = this.gltf.animations;
  3786. if (!animations) {
  3787. return Promise.resolve();
  3788. }
  3789. var promises = new Array();
  3790. for (var index = 0; index < animations.length; index++) {
  3791. var animation = animations[index];
  3792. promises.push(this.loadAnimationAsync("#/animations/" + animation.index, animation));
  3793. }
  3794. return Promise.all(promises).then(function () { });
  3795. };
  3796. /**
  3797. * Loads a glTF animation.
  3798. * @param context The context when loading the asset
  3799. * @param animation The glTF animation property
  3800. * @returns A promise that resolves with the loaded Babylon animation group when the load is complete
  3801. */
  3802. GLTFLoader.prototype.loadAnimationAsync = function (context, animation) {
  3803. var promise = this._extensionsLoadAnimationAsync(context, animation);
  3804. if (promise) {
  3805. return promise;
  3806. }
  3807. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation.index, this.babylonScene);
  3808. animation._babylonAnimationGroup = babylonAnimationGroup;
  3809. var promises = new Array();
  3810. ArrayItem.Assign(animation.channels);
  3811. ArrayItem.Assign(animation.samplers);
  3812. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  3813. var channel = _a[_i];
  3814. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel.index, context, animation, channel, babylonAnimationGroup));
  3815. }
  3816. return Promise.all(promises).then(function () {
  3817. babylonAnimationGroup.normalize(0);
  3818. return babylonAnimationGroup;
  3819. });
  3820. };
  3821. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  3822. var _this = this;
  3823. var targetNode = ArrayItem.Get(context + "/target/node", this.gltf.nodes, channel.target.node);
  3824. // Ignore animations that have no animation targets.
  3825. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  3826. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  3827. return Promise.resolve();
  3828. }
  3829. // Ignore animations targeting TRS of skinned nodes.
  3830. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  3831. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  3832. return Promise.resolve();
  3833. }
  3834. var sampler = ArrayItem.Get(context + "/sampler", animation.samplers, channel.sampler);
  3835. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  3836. var targetPath;
  3837. var animationType;
  3838. switch (channel.target.path) {
  3839. case "translation" /* TRANSLATION */: {
  3840. targetPath = "position";
  3841. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  3842. break;
  3843. }
  3844. case "rotation" /* ROTATION */: {
  3845. targetPath = "rotationQuaternion";
  3846. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  3847. break;
  3848. }
  3849. case "scale" /* SCALE */: {
  3850. targetPath = "scaling";
  3851. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  3852. break;
  3853. }
  3854. case "weights" /* WEIGHTS */: {
  3855. targetPath = "influence";
  3856. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  3857. break;
  3858. }
  3859. default: {
  3860. throw new Error(context + "/target/path: Invalid value (" + channel.target.path + ")");
  3861. }
  3862. }
  3863. var outputBufferOffset = 0;
  3864. var getNextOutputValue;
  3865. switch (targetPath) {
  3866. case "position": {
  3867. getNextOutputValue = function () {
  3868. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  3869. outputBufferOffset += 3;
  3870. return value;
  3871. };
  3872. break;
  3873. }
  3874. case "rotationQuaternion": {
  3875. getNextOutputValue = function () {
  3876. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  3877. outputBufferOffset += 4;
  3878. return value;
  3879. };
  3880. break;
  3881. }
  3882. case "scaling": {
  3883. getNextOutputValue = function () {
  3884. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  3885. outputBufferOffset += 3;
  3886. return value;
  3887. };
  3888. break;
  3889. }
  3890. case "influence": {
  3891. getNextOutputValue = function () {
  3892. var value = new Array(targetNode._numMorphTargets);
  3893. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  3894. value[i] = data.output[outputBufferOffset++];
  3895. }
  3896. return value;
  3897. };
  3898. break;
  3899. }
  3900. }
  3901. var getNextKey;
  3902. switch (data.interpolation) {
  3903. case "STEP" /* STEP */: {
  3904. getNextKey = function (frameIndex) { return ({
  3905. frame: data.input[frameIndex],
  3906. value: getNextOutputValue(),
  3907. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  3908. }); };
  3909. break;
  3910. }
  3911. case "LINEAR" /* LINEAR */: {
  3912. getNextKey = function (frameIndex) { return ({
  3913. frame: data.input[frameIndex],
  3914. value: getNextOutputValue()
  3915. }); };
  3916. break;
  3917. }
  3918. case "CUBICSPLINE" /* CUBICSPLINE */: {
  3919. getNextKey = function (frameIndex) { return ({
  3920. frame: data.input[frameIndex],
  3921. inTangent: getNextOutputValue(),
  3922. value: getNextOutputValue(),
  3923. outTangent: getNextOutputValue()
  3924. }); };
  3925. break;
  3926. }
  3927. }
  3928. var keys = new Array(data.input.length);
  3929. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  3930. keys[frameIndex] = getNextKey(frameIndex);
  3931. }
  3932. if (targetPath === "influence") {
  3933. var _loop_2 = function (targetIndex) {
  3934. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  3935. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  3936. babylonAnimation.setKeys(keys.map(function (key) { return ({
  3937. frame: key.frame,
  3938. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  3939. value: key.value[targetIndex],
  3940. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  3941. }); }));
  3942. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  3943. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  3944. var babylonAnimationClone = babylonAnimation.clone();
  3945. morphTarget.animations.push(babylonAnimationClone);
  3946. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  3947. });
  3948. };
  3949. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  3950. _loop_2(targetIndex);
  3951. }
  3952. }
  3953. else {
  3954. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  3955. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  3956. babylonAnimation.setKeys(keys);
  3957. if (targetNode._babylonBones) {
  3958. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  3959. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  3960. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  3961. babylonAnimationTarget.animations.push(babylonAnimation);
  3962. }
  3963. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  3964. }
  3965. else {
  3966. targetNode._babylonMesh.animations.push(babylonAnimation);
  3967. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  3968. }
  3969. }
  3970. });
  3971. };
  3972. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  3973. if (sampler._data) {
  3974. return sampler._data;
  3975. }
  3976. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  3977. switch (interpolation) {
  3978. case "STEP" /* STEP */:
  3979. case "LINEAR" /* LINEAR */:
  3980. case "CUBICSPLINE" /* CUBICSPLINE */: {
  3981. break;
  3982. }
  3983. default: {
  3984. throw new Error(context + "/interpolation: Invalid value (" + sampler.interpolation + ")");
  3985. }
  3986. }
  3987. var inputAccessor = ArrayItem.Get(context + "/input", this.gltf.accessors, sampler.input);
  3988. var outputAccessor = ArrayItem.Get(context + "/output", this.gltf.accessors, sampler.output);
  3989. sampler._data = Promise.all([
  3990. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor),
  3991. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor)
  3992. ]).then(function (_a) {
  3993. var inputData = _a[0], outputData = _a[1];
  3994. return {
  3995. input: inputData,
  3996. interpolation: interpolation,
  3997. output: outputData,
  3998. };
  3999. });
  4000. return sampler._data;
  4001. };
  4002. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  4003. if (buffer._data) {
  4004. return buffer._data;
  4005. }
  4006. if (!buffer.uri) {
  4007. throw new Error(context + "/uri: Value is missing");
  4008. }
  4009. buffer._data = this.loadUriAsync(context + "/uri", buffer.uri);
  4010. return buffer._data;
  4011. };
  4012. /**
  4013. * Loads a glTF buffer view.
  4014. * @param context The context when loading the asset
  4015. * @param bufferView The glTF buffer view property
  4016. * @returns A promise that resolves with the loaded data when the load is complete
  4017. */
  4018. GLTFLoader.prototype.loadBufferViewAsync = function (context, bufferView) {
  4019. if (bufferView._data) {
  4020. return bufferView._data;
  4021. }
  4022. var buffer = ArrayItem.Get(context + "/buffer", this.gltf.buffers, bufferView.buffer);
  4023. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer.index, buffer).then(function (data) {
  4024. try {
  4025. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  4026. }
  4027. catch (e) {
  4028. throw new Error(context + ": " + e.message);
  4029. }
  4030. });
  4031. return bufferView._data;
  4032. };
  4033. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  4034. if (accessor.type !== "SCALAR" /* SCALAR */) {
  4035. throw new Error(context + "/type: Invalid value " + accessor.type);
  4036. }
  4037. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  4038. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  4039. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  4040. throw new Error(context + "/componentType: Invalid value " + accessor.componentType);
  4041. }
  4042. if (accessor._data) {
  4043. return accessor._data;
  4044. }
  4045. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  4046. accessor._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  4047. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  4048. });
  4049. return accessor._data;
  4050. };
  4051. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  4052. // TODO: support normalized and stride
  4053. var _this = this;
  4054. if (accessor.componentType !== 5126 /* FLOAT */) {
  4055. throw new Error("Invalid component type " + accessor.componentType);
  4056. }
  4057. if (accessor._data) {
  4058. return accessor._data;
  4059. }
  4060. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  4061. var length = numComponents * accessor.count;
  4062. if (accessor.bufferView == undefined) {
  4063. accessor._data = Promise.resolve(new Float32Array(length));
  4064. }
  4065. else {
  4066. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  4067. accessor._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  4068. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  4069. });
  4070. }
  4071. if (accessor.sparse) {
  4072. var sparse_1 = accessor.sparse;
  4073. accessor._data = accessor._data.then(function (data) {
  4074. var indicesBufferView = ArrayItem.Get(context + "/sparse/indices/bufferView", _this.gltf.bufferViews, sparse_1.indices.bufferView);
  4075. var valuesBufferView = ArrayItem.Get(context + "/sparse/values/bufferView", _this.gltf.bufferViews, sparse_1.values.bufferView);
  4076. return Promise.all([
  4077. _this.loadBufferViewAsync("#/bufferViews/" + indicesBufferView.index, indicesBufferView),
  4078. _this.loadBufferViewAsync("#/bufferViews/" + valuesBufferView.index, valuesBufferView)
  4079. ]).then(function (_a) {
  4080. var indicesData = _a[0], valuesData = _a[1];
  4081. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  4082. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  4083. var valuesIndex = 0;
  4084. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  4085. var dataIndex = indices[indicesIndex] * numComponents;
  4086. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  4087. data[dataIndex++] = values[valuesIndex++];
  4088. }
  4089. }
  4090. return data;
  4091. });
  4092. });
  4093. }
  4094. return accessor._data;
  4095. };
  4096. GLTFLoader.prototype._loadVertexBufferViewAsync = function (bufferView, kind) {
  4097. var _this = this;
  4098. if (bufferView._babylonBuffer) {
  4099. return bufferView._babylonBuffer;
  4100. }
  4101. bufferView._babylonBuffer = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  4102. return new BABYLON.Buffer(_this.babylonScene.getEngine(), data, false);
  4103. });
  4104. return bufferView._babylonBuffer;
  4105. };
  4106. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  4107. var _this = this;
  4108. if (accessor._babylonVertexBuffer) {
  4109. return accessor._babylonVertexBuffer;
  4110. }
  4111. if (accessor.sparse) {
  4112. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  4113. return new BABYLON.VertexBuffer(_this.babylonScene.getEngine(), data, kind, false);
  4114. });
  4115. }
  4116. // HACK: If byte offset is not a multiple of component type byte length then load as a float array instead of using Babylon buffers.
  4117. else if (accessor.byteOffset && accessor.byteOffset % BABYLON.VertexBuffer.GetTypeByteLength(accessor.componentType) !== 0) {
  4118. BABYLON.Tools.Warn("Accessor byte offset is not a multiple of component type byte length");
  4119. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  4120. return new BABYLON.VertexBuffer(_this.babylonScene.getEngine(), data, kind, false);
  4121. });
  4122. }
  4123. else {
  4124. var bufferView_1 = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  4125. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync(bufferView_1, kind).then(function (babylonBuffer) {
  4126. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  4127. return new BABYLON.VertexBuffer(_this.babylonScene.getEngine(), babylonBuffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  4128. });
  4129. }
  4130. return accessor._babylonVertexBuffer;
  4131. };
  4132. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, properties, babylonMaterial) {
  4133. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  4134. throw new Error(context + ": Material type not supported");
  4135. }
  4136. var promises = new Array();
  4137. if (properties) {
  4138. if (properties.baseColorFactor) {
  4139. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  4140. babylonMaterial.alpha = properties.baseColorFactor[3];
  4141. }
  4142. else {
  4143. babylonMaterial.albedoColor = BABYLON.Color3.White();
  4144. }
  4145. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  4146. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  4147. if (properties.baseColorTexture) {
  4148. promises.push(this.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  4149. babylonMaterial.albedoTexture = texture;
  4150. }));
  4151. }
  4152. if (properties.metallicRoughnessTexture) {
  4153. promises.push(this.loadTextureInfoAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  4154. babylonMaterial.metallicTexture = texture;
  4155. }));
  4156. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  4157. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  4158. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  4159. }
  4160. }
  4161. return Promise.all(promises).then(function () { });
  4162. };
  4163. /** @hidden */
  4164. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  4165. if (assign === void 0) { assign = function () { }; }
  4166. var extensionPromise = this._extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign);
  4167. if (extensionPromise) {
  4168. return extensionPromise;
  4169. }
  4170. material._babylonData = material._babylonData || {};
  4171. var babylonData = material._babylonData[babylonDrawMode];
  4172. if (!babylonData) {
  4173. this.logOpen(context + " " + (material.name || ""));
  4174. var babylonMaterial = this.createMaterial(context, material, babylonDrawMode);
  4175. babylonData = {
  4176. material: babylonMaterial,
  4177. meshes: [],
  4178. promise: this.loadMaterialPropertiesAsync(context, material, babylonMaterial)
  4179. };
  4180. material._babylonData[babylonDrawMode] = babylonData;
  4181. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  4182. this.logClose();
  4183. }
  4184. babylonData.meshes.push(babylonMesh);
  4185. babylonMesh.onDisposeObservable.addOnce(function () {
  4186. var index = babylonData.meshes.indexOf(babylonMesh);
  4187. if (index !== -1) {
  4188. babylonData.meshes.splice(index, 1);
  4189. }
  4190. });
  4191. assign(babylonData.material);
  4192. return babylonData.promise.then(function () {
  4193. return babylonData.material;
  4194. });
  4195. };
  4196. GLTFLoader.prototype._createDefaultMaterial = function (name, babylonDrawMode) {
  4197. var babylonMaterial = new BABYLON.PBRMaterial(name, this.babylonScene);
  4198. babylonMaterial.sideOrientation = this.babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  4199. babylonMaterial.fillMode = babylonDrawMode;
  4200. babylonMaterial.enableSpecularAntiAliasing = true;
  4201. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  4202. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  4203. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  4204. babylonMaterial.metallic = 1;
  4205. babylonMaterial.roughness = 1;
  4206. return babylonMaterial;
  4207. };
  4208. /**
  4209. * Creates a Babylon material from a glTF material.
  4210. * @param context The context when loading the asset
  4211. * @param material The glTF material property
  4212. * @param babylonDrawMode The draw mode for the Babylon material
  4213. * @returns The Babylon material
  4214. */
  4215. GLTFLoader.prototype.createMaterial = function (context, material, babylonDrawMode) {
  4216. var extensionPromise = this._extensionsCreateMaterial(context, material, babylonDrawMode);
  4217. if (extensionPromise) {
  4218. return extensionPromise;
  4219. }
  4220. var name = material.name || "material" + material.index;
  4221. return this._createDefaultMaterial(name, babylonDrawMode);
  4222. };
  4223. /**
  4224. * Loads properties from a glTF material into a Babylon material.
  4225. * @param context The context when loading the asset
  4226. * @param material The glTF material property
  4227. * @param babylonMaterial The Babylon material
  4228. * @returns A promise that resolves when the load is complete
  4229. */
  4230. GLTFLoader.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  4231. var extensionPromise = this._extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial);
  4232. if (extensionPromise) {
  4233. return extensionPromise;
  4234. }
  4235. var promises = new Array();
  4236. promises.push(this.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  4237. if (material.pbrMetallicRoughness) {
  4238. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context + "/pbrMetallicRoughness", material.pbrMetallicRoughness, babylonMaterial));
  4239. }
  4240. this.loadMaterialAlphaProperties(context, material, babylonMaterial);
  4241. return Promise.all(promises).then(function () { });
  4242. };
  4243. /**
  4244. * Loads the normal, occlusion, and emissive properties from a glTF material into a Babylon material.
  4245. * @param context The context when loading the asset
  4246. * @param material The glTF material property
  4247. * @param babylonMaterial The Babylon material
  4248. * @returns A promise that resolves when the load is complete
  4249. */
  4250. GLTFLoader.prototype.loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  4251. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  4252. throw new Error(context + ": Material type not supported");
  4253. }
  4254. var promises = new Array();
  4255. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  4256. if (material.doubleSided) {
  4257. babylonMaterial.backFaceCulling = false;
  4258. babylonMaterial.twoSidedLighting = true;
  4259. }
  4260. if (material.normalTexture) {
  4261. promises.push(this.loadTextureInfoAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  4262. babylonMaterial.bumpTexture = texture;
  4263. }));
  4264. babylonMaterial.invertNormalMapX = !this.babylonScene.useRightHandedSystem;
  4265. babylonMaterial.invertNormalMapY = this.babylonScene.useRightHandedSystem;
  4266. if (material.normalTexture.scale != undefined) {
  4267. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  4268. }
  4269. }
  4270. if (material.occlusionTexture) {
  4271. promises.push(this.loadTextureInfoAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  4272. babylonMaterial.ambientTexture = texture;
  4273. }));
  4274. babylonMaterial.useAmbientInGrayScale = true;
  4275. if (material.occlusionTexture.strength != undefined) {
  4276. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  4277. }
  4278. }
  4279. if (material.emissiveTexture) {
  4280. promises.push(this.loadTextureInfoAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  4281. babylonMaterial.emissiveTexture = texture;
  4282. }));
  4283. }
  4284. return Promise.all(promises).then(function () { });
  4285. };
  4286. /**
  4287. * Loads the alpha properties from a glTF material into a Babylon material.
  4288. * Must be called after the setting the albedo texture of the Babylon material when the material has an albedo texture.
  4289. * @param context The context when loading the asset
  4290. * @param material The glTF material property
  4291. * @param babylonMaterial The Babylon material
  4292. */
  4293. GLTFLoader.prototype.loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  4294. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  4295. throw new Error(context + ": Material type not supported");
  4296. }
  4297. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  4298. switch (alphaMode) {
  4299. case "OPAQUE" /* OPAQUE */: {
  4300. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  4301. break;
  4302. }
  4303. case "MASK" /* MASK */: {
  4304. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  4305. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  4306. if (babylonMaterial.albedoTexture) {
  4307. babylonMaterial.albedoTexture.hasAlpha = true;
  4308. }
  4309. break;
  4310. }
  4311. case "BLEND" /* BLEND */: {
  4312. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  4313. if (babylonMaterial.albedoTexture) {
  4314. babylonMaterial.albedoTexture.hasAlpha = true;
  4315. babylonMaterial.useAlphaFromAlbedoTexture = true;
  4316. }
  4317. break;
  4318. }
  4319. default: {
  4320. throw new Error(context + "/alphaMode: Invalid value (" + material.alphaMode + ")");
  4321. }
  4322. }
  4323. };
  4324. /**
  4325. * Loads a glTF texture info.
  4326. * @param context The context when loading the asset
  4327. * @param textureInfo The glTF texture info property
  4328. * @param assign A function called synchronously after parsing the glTF properties
  4329. * @returns A promise that resolves with the loaded Babylon texture when the load is complete
  4330. */
  4331. GLTFLoader.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) {
  4332. if (assign === void 0) { assign = function () { }; }
  4333. var extensionPromise = this._extensionsLoadTextureInfoAsync(context, textureInfo, assign);
  4334. if (extensionPromise) {
  4335. return extensionPromise;
  4336. }
  4337. this.logOpen("" + context);
  4338. var texture = ArrayItem.Get(context + "/index", this.gltf.textures, textureInfo.index);
  4339. var promise = this._loadTextureAsync("#/textures/" + textureInfo.index, texture, function (babylonTexture) {
  4340. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  4341. assign(babylonTexture);
  4342. });
  4343. this.logClose();
  4344. return promise;
  4345. };
  4346. GLTFLoader.prototype._loadTextureAsync = function (context, texture, assign) {
  4347. var _this = this;
  4348. if (assign === void 0) { assign = function () { }; }
  4349. var promises = new Array();
  4350. this.logOpen(context + " " + (texture.name || ""));
  4351. var sampler = (texture.sampler == undefined ? GLTFLoader._DefaultSampler : ArrayItem.Get(context + "/sampler", this.gltf.samplers, texture.sampler));
  4352. var samplerData = this._loadSampler("#/samplers/" + sampler.index, sampler);
  4353. var deferred = new BABYLON.Deferred();
  4354. var babylonTexture = new BABYLON.Texture(null, this.babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  4355. if (!_this._disposed) {
  4356. deferred.resolve();
  4357. }
  4358. }, function (message, exception) {
  4359. if (!_this._disposed) {
  4360. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  4361. }
  4362. });
  4363. promises.push(deferred.promise);
  4364. babylonTexture.name = texture.name || "texture" + texture.index;
  4365. babylonTexture.wrapU = samplerData.wrapU;
  4366. babylonTexture.wrapV = samplerData.wrapV;
  4367. var image = ArrayItem.Get(context + "/source", this.gltf.images, texture.source);
  4368. promises.push(this.loadImageAsync("#/images/" + image.index, image).then(function (data) {
  4369. var name = image.uri || _this._fileName + "#image" + image.index;
  4370. var dataUrl = "data:" + _this._uniqueRootUrl + name;
  4371. babylonTexture.updateURL(dataUrl, new Blob([data], { type: image.mimeType }));
  4372. }));
  4373. assign(babylonTexture);
  4374. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  4375. this.logClose();
  4376. return Promise.all(promises).then(function () {
  4377. return babylonTexture;
  4378. });
  4379. };
  4380. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  4381. if (!sampler._data) {
  4382. sampler._data = {
  4383. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  4384. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler),
  4385. wrapU: GLTFLoader._GetTextureWrapMode(context + "/wrapS", sampler.wrapS),
  4386. wrapV: GLTFLoader._GetTextureWrapMode(context + "/wrapT", sampler.wrapT)
  4387. };
  4388. }
  4389. ;
  4390. return sampler._data;
  4391. };
  4392. /**
  4393. * Loads a glTF image.
  4394. * @param context The context when loading the asset
  4395. * @param image The glTF image property
  4396. * @returns A promise that resolves with the loaded data when the load is complete
  4397. */
  4398. GLTFLoader.prototype.loadImageAsync = function (context, image) {
  4399. if (!image._data) {
  4400. this.logOpen(context + " " + (image.name || ""));
  4401. if (image.uri) {
  4402. image._data = this.loadUriAsync(context + "/uri", image.uri);
  4403. }
  4404. else {
  4405. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, image.bufferView);
  4406. image._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView);
  4407. }
  4408. this.logClose();
  4409. }
  4410. return image._data;
  4411. };
  4412. /**
  4413. * Loads a glTF uri.
  4414. * @param context The context when loading the asset
  4415. * @param uri The base64 or relative uri
  4416. * @returns A promise that resolves with the loaded data when the load is complete
  4417. */
  4418. GLTFLoader.prototype.loadUriAsync = function (context, uri) {
  4419. var _this = this;
  4420. var extensionPromise = this._extensionsLoadUriAsync(context, uri);
  4421. if (extensionPromise) {
  4422. return extensionPromise;
  4423. }
  4424. if (!GLTFLoader._ValidateUri(uri)) {
  4425. throw new Error(context + ": '" + uri + "' is invalid");
  4426. }
  4427. if (BABYLON.Tools.IsBase64(uri)) {
  4428. var data = new Uint8Array(BABYLON.Tools.DecodeBase64(uri));
  4429. this.log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)");
  4430. return Promise.resolve(data);
  4431. }
  4432. this.log("Loading " + uri);
  4433. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  4434. return new Promise(function (resolve, reject) {
  4435. if (!_this._disposed) {
  4436. var request_1 = BABYLON.Tools.LoadFile(url, function (fileData) {
  4437. if (!_this._disposed) {
  4438. var data = new Uint8Array(fileData);
  4439. _this.log("Loaded " + uri + " (" + data.length + " bytes)");
  4440. resolve(data);
  4441. }
  4442. }, function (event) {
  4443. if (!_this._disposed) {
  4444. if (request_1) {
  4445. request_1._lengthComputable = event.lengthComputable;
  4446. request_1._loaded = event.loaded;
  4447. request_1._total = event.total;
  4448. }
  4449. if (_this._state === BABYLON.GLTFLoaderState.LOADING) {
  4450. try {
  4451. _this._onProgress();
  4452. }
  4453. catch (e) {
  4454. reject(e);
  4455. }
  4456. }
  4457. }
  4458. }, _this.babylonScene.database, true, function (request, exception) {
  4459. if (!_this._disposed) {
  4460. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  4461. }
  4462. });
  4463. _this._requests.push(request_1);
  4464. }
  4465. });
  4466. });
  4467. };
  4468. GLTFLoader.prototype._onProgress = function () {
  4469. if (!this._progressCallback) {
  4470. return;
  4471. }
  4472. var lengthComputable = true;
  4473. var loaded = 0;
  4474. var total = 0;
  4475. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  4476. var request = _a[_i];
  4477. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  4478. return;
  4479. }
  4480. lengthComputable = lengthComputable && request._lengthComputable;
  4481. loaded += request._loaded;
  4482. total += request._total;
  4483. }
  4484. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  4485. };
  4486. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  4487. // Set defaults if undefined
  4488. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  4489. switch (mode) {
  4490. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  4491. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  4492. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  4493. default:
  4494. BABYLON.Tools.Warn(context + ": Invalid value (" + mode + ")");
  4495. return BABYLON.Texture.WRAP_ADDRESSMODE;
  4496. }
  4497. };
  4498. GLTFLoader._GetTextureSamplingMode = function (context, sampler) {
  4499. // Set defaults if undefined
  4500. var magFilter = sampler.magFilter == undefined ? 9729 /* LINEAR */ : sampler.magFilter;
  4501. var minFilter = sampler.minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : sampler.minFilter;
  4502. if (magFilter === 9729 /* LINEAR */) {
  4503. switch (minFilter) {
  4504. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  4505. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  4506. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  4507. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  4508. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  4509. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  4510. default:
  4511. BABYLON.Tools.Warn(context + "/minFilter: Invalid value (" + minFilter + ")");
  4512. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  4513. }
  4514. }
  4515. else {
  4516. if (magFilter !== 9728 /* NEAREST */) {
  4517. BABYLON.Tools.Warn(context + "/magFilter: Invalid value (" + magFilter + ")");
  4518. }
  4519. switch (minFilter) {
  4520. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  4521. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  4522. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  4523. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  4524. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  4525. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  4526. default:
  4527. BABYLON.Tools.Warn(context + "/minFilter: Invalid value (" + minFilter + ")");
  4528. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  4529. }
  4530. }
  4531. };
  4532. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  4533. var buffer = bufferView.buffer;
  4534. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  4535. try {
  4536. switch (componentType) {
  4537. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  4538. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  4539. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  4540. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  4541. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  4542. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  4543. default: throw new Error("Invalid component type " + componentType);
  4544. }
  4545. }
  4546. catch (e) {
  4547. throw new Error(context + ": " + e);
  4548. }
  4549. };
  4550. GLTFLoader._GetNumComponents = function (context, type) {
  4551. switch (type) {
  4552. case "SCALAR": return 1;
  4553. case "VEC2": return 2;
  4554. case "VEC3": return 3;
  4555. case "VEC4": return 4;
  4556. case "MAT2": return 4;
  4557. case "MAT3": return 9;
  4558. case "MAT4": return 16;
  4559. }
  4560. throw new Error(context + ": Invalid type (" + type + ")");
  4561. };
  4562. GLTFLoader._ValidateUri = function (uri) {
  4563. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  4564. };
  4565. GLTFLoader._GetDrawMode = function (context, mode) {
  4566. if (mode == undefined) {
  4567. mode = 4 /* TRIANGLES */;
  4568. }
  4569. switch (mode) {
  4570. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  4571. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  4572. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  4573. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  4574. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  4575. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  4576. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  4577. }
  4578. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  4579. };
  4580. GLTFLoader.prototype._compileMaterialsAsync = function () {
  4581. var _this = this;
  4582. this._parent._startPerformanceCounter("Compile materials");
  4583. var promises = new Array();
  4584. if (this.gltf.materials) {
  4585. for (var _i = 0, _a = this.gltf.materials; _i < _a.length; _i++) {
  4586. var material = _a[_i];
  4587. if (material._babylonData) {
  4588. for (var babylonDrawMode in material._babylonData) {
  4589. var babylonData = material._babylonData[babylonDrawMode];
  4590. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  4591. var babylonMesh = _c[_b];
  4592. // Ensure nonUniformScaling is set if necessary.
  4593. babylonMesh.computeWorldMatrix(true);
  4594. var babylonMaterial = babylonData.material;
  4595. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  4596. if (this._parent.useClipPlane) {
  4597. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  4598. }
  4599. }
  4600. }
  4601. }
  4602. }
  4603. }
  4604. return Promise.all(promises).then(function () {
  4605. _this._parent._endPerformanceCounter("Compile materials");
  4606. });
  4607. };
  4608. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  4609. var _this = this;
  4610. this._parent._startPerformanceCounter("Compile shadow generators");
  4611. var promises = new Array();
  4612. var lights = this.babylonScene.lights;
  4613. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  4614. var light = lights_1[_i];
  4615. var generator = light.getShadowGenerator();
  4616. if (generator) {
  4617. promises.push(generator.forceCompilationAsync());
  4618. }
  4619. }
  4620. return Promise.all(promises).then(function () {
  4621. _this._parent._endPerformanceCounter("Compile shadow generators");
  4622. });
  4623. };
  4624. GLTFLoader.prototype._forEachExtensions = function (action) {
  4625. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  4626. var name_4 = _a[_i];
  4627. var extension = this._extensions[name_4];
  4628. if (extension.enabled) {
  4629. action(extension);
  4630. }
  4631. }
  4632. };
  4633. GLTFLoader.prototype._applyExtensions = function (property, actionAsync) {
  4634. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  4635. var name_5 = _a[_i];
  4636. var extension = this._extensions[name_5];
  4637. if (extension.enabled) {
  4638. var loaderProperty = property;
  4639. loaderProperty._activeLoaderExtensions = loaderProperty._activeLoaderExtensions || {};
  4640. var activeLoaderExtensions = loaderProperty._activeLoaderExtensions;
  4641. if (!activeLoaderExtensions[name_5]) {
  4642. activeLoaderExtensions[name_5] = true;
  4643. try {
  4644. var result = actionAsync(extension);
  4645. if (result) {
  4646. return result;
  4647. }
  4648. }
  4649. finally {
  4650. delete activeLoaderExtensions[name_5];
  4651. }
  4652. }
  4653. }
  4654. }
  4655. return null;
  4656. };
  4657. GLTFLoader.prototype._extensionsOnLoading = function () {
  4658. this._forEachExtensions(function (extension) { return extension.onLoading && extension.onLoading(); });
  4659. };
  4660. GLTFLoader.prototype._extensionsOnReady = function () {
  4661. this._forEachExtensions(function (extension) { return extension.onReady && extension.onReady(); });
  4662. };
  4663. GLTFLoader.prototype._extensionsLoadSceneAsync = function (context, scene) {
  4664. return this._applyExtensions(scene, function (extension) { return extension.loadSceneAsync && extension.loadSceneAsync(context, scene); });
  4665. };
  4666. GLTFLoader.prototype._extensionsLoadNodeAsync = function (context, node, assign) {
  4667. return this._applyExtensions(node, function (extension) { return extension.loadNodeAsync && extension.loadNodeAsync(context, node, assign); });
  4668. };
  4669. GLTFLoader.prototype._extensionsLoadCameraAsync = function (context, camera, assign) {
  4670. return this._applyExtensions(camera, function (extension) { return extension.loadCameraAsync && extension.loadCameraAsync(context, camera, assign); });
  4671. };
  4672. GLTFLoader.prototype._extensionsLoadVertexDataAsync = function (context, primitive, babylonMesh) {
  4673. return this._applyExtensions(primitive, function (extension) { return extension._loadVertexDataAsync && extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  4674. };
  4675. GLTFLoader.prototype._extensionsLoadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  4676. return this._applyExtensions(material, function (extension) { return extension._loadMaterialAsync && extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  4677. };
  4678. GLTFLoader.prototype._extensionsCreateMaterial = function (context, material, babylonDrawMode) {
  4679. return this._applyExtensions({}, function (extension) { return extension.createMaterial && extension.createMaterial(context, material, babylonDrawMode); });
  4680. };
  4681. GLTFLoader.prototype._extensionsLoadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  4682. return this._applyExtensions(material, function (extension) { return extension.loadMaterialPropertiesAsync && extension.loadMaterialPropertiesAsync(context, material, babylonMaterial); });
  4683. };
  4684. GLTFLoader.prototype._extensionsLoadTextureInfoAsync = function (context, textureInfo, assign) {
  4685. return this._applyExtensions(textureInfo, function (extension) { return extension.loadTextureInfoAsync && extension.loadTextureInfoAsync(context, textureInfo, assign); });
  4686. };
  4687. GLTFLoader.prototype._extensionsLoadAnimationAsync = function (context, animation) {
  4688. return this._applyExtensions(animation, function (extension) { return extension.loadAnimationAsync && extension.loadAnimationAsync(context, animation); });
  4689. };
  4690. GLTFLoader.prototype._extensionsLoadUriAsync = function (context, uri) {
  4691. return this._applyExtensions({}, function (extension) { return extension._loadUriAsync && extension._loadUriAsync(context, uri); });
  4692. };
  4693. /**
  4694. * Helper method called by a loader extension to load an glTF extension.
  4695. * @param context The context when loading the asset
  4696. * @param property The glTF property to load the extension from
  4697. * @param extensionName The name of the extension to load
  4698. * @param actionAsync The action to run
  4699. * @returns The promise returned by actionAsync or null if the extension does not exist
  4700. */
  4701. GLTFLoader.LoadExtensionAsync = function (context, property, extensionName, actionAsync) {
  4702. if (!property.extensions) {
  4703. return null;
  4704. }
  4705. var extensions = property.extensions;
  4706. var extension = extensions[extensionName];
  4707. if (!extension) {
  4708. return null;
  4709. }
  4710. return actionAsync(context + "/extensions/" + extensionName, extension);
  4711. };
  4712. /**
  4713. * Helper method called by a loader extension to load a glTF extra.
  4714. * @param context The context when loading the asset
  4715. * @param property The glTF property to load the extra from
  4716. * @param extensionName The name of the extension to load
  4717. * @param actionAsync The action to run
  4718. * @returns The promise returned by actionAsync or null if the extra does not exist
  4719. */
  4720. GLTFLoader.LoadExtraAsync = function (context, property, extensionName, actionAsync) {
  4721. if (!property.extras) {
  4722. return null;
  4723. }
  4724. var extras = property.extras;
  4725. var extra = extras[extensionName];
  4726. if (!extra) {
  4727. return null;
  4728. }
  4729. return actionAsync(context + "/extras/" + extensionName, extra);
  4730. };
  4731. /**
  4732. * Increments the indentation level and logs a message.
  4733. * @param message The message to log
  4734. */
  4735. GLTFLoader.prototype.logOpen = function (message) {
  4736. this._parent._logOpen(message);
  4737. };
  4738. /**
  4739. * Decrements the indentation level.
  4740. */
  4741. GLTFLoader.prototype.logClose = function () {
  4742. this._parent._logClose();
  4743. };
  4744. /**
  4745. * Logs a message
  4746. * @param message The message to log
  4747. */
  4748. GLTFLoader.prototype.log = function (message) {
  4749. this._parent._log(message);
  4750. };
  4751. /**
  4752. * Starts a performance counter.
  4753. * @param counterName The name of the performance counter
  4754. */
  4755. GLTFLoader.prototype.startPerformanceCounter = function (counterName) {
  4756. this._parent._startPerformanceCounter(counterName);
  4757. };
  4758. /**
  4759. * Ends a performance counter.
  4760. * @param counterName The name of the performance counter
  4761. */
  4762. GLTFLoader.prototype.endPerformanceCounter = function (counterName) {
  4763. this._parent._endPerformanceCounter(counterName);
  4764. };
  4765. GLTFLoader._DefaultSampler = { index: -1 };
  4766. GLTFLoader._ExtensionNames = new Array();
  4767. GLTFLoader._ExtensionFactories = {};
  4768. return GLTFLoader;
  4769. }());
  4770. GLTF2.GLTFLoader = GLTFLoader;
  4771. BABYLON.GLTFFileLoader._CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  4772. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4773. })(BABYLON || (BABYLON = {}));
  4774. //# sourceMappingURL=babylon.glTFLoader.js.map
  4775. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  4776. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  4777. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4778. var BABYLON;
  4779. (function (BABYLON) {
  4780. var GLTF2;
  4781. (function (GLTF2) {
  4782. var Loader;
  4783. (function (Loader) {
  4784. var Extensions;
  4785. (function (Extensions) {
  4786. var NAME = "MSFT_lod";
  4787. /**
  4788. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  4789. */
  4790. var MSFT_lod = /** @class */ (function () {
  4791. /** @hidden */
  4792. function MSFT_lod(loader) {
  4793. /** The name of this extension. */
  4794. this.name = NAME;
  4795. /** Defines whether this extension is enabled. */
  4796. this.enabled = true;
  4797. /**
  4798. * Maximum number of LODs to load, starting from the lowest LOD.
  4799. */
  4800. this.maxLODsToLoad = Number.MAX_VALUE;
  4801. /**
  4802. * Observable raised when all node LODs of one level are loaded.
  4803. * The event data is the index of the loaded LOD starting from zero.
  4804. * Dispose the loader to cancel the loading of the next level of LODs.
  4805. */
  4806. this.onNodeLODsLoadedObservable = new BABYLON.Observable();
  4807. /**
  4808. * Observable raised when all material LODs of one level are loaded.
  4809. * The event data is the index of the loaded LOD starting from zero.
  4810. * Dispose the loader to cancel the loading of the next level of LODs.
  4811. */
  4812. this.onMaterialLODsLoadedObservable = new BABYLON.Observable();
  4813. this._nodeIndexLOD = null;
  4814. this._nodeSignalLODs = new Array();
  4815. this._nodePromiseLODs = new Array();
  4816. this._materialIndexLOD = null;
  4817. this._materialSignalLODs = new Array();
  4818. this._materialPromiseLODs = new Array();
  4819. this._loader = loader;
  4820. }
  4821. /** @hidden */
  4822. MSFT_lod.prototype.dispose = function () {
  4823. delete this._loader;
  4824. this._nodeIndexLOD = null;
  4825. this._nodeSignalLODs.length = 0;
  4826. this._nodePromiseLODs.length = 0;
  4827. this._materialIndexLOD = null;
  4828. this._materialSignalLODs.length = 0;
  4829. this._materialPromiseLODs.length = 0;
  4830. this.onMaterialLODsLoadedObservable.clear();
  4831. this.onNodeLODsLoadedObservable.clear();
  4832. };
  4833. /** @hidden */
  4834. MSFT_lod.prototype.onReady = function () {
  4835. var _this = this;
  4836. var _loop_1 = function (indexLOD) {
  4837. var promise = Promise.all(this_1._nodePromiseLODs[indexLOD]).then(function () {
  4838. if (indexLOD !== 0) {
  4839. _this._loader.endPerformanceCounter("Node LOD " + indexLOD);
  4840. }
  4841. _this._loader.log("Loaded node LOD " + indexLOD);
  4842. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  4843. if (indexLOD !== _this._nodePromiseLODs.length - 1) {
  4844. _this._loader.startPerformanceCounter("Node LOD " + (indexLOD + 1));
  4845. if (_this._nodeSignalLODs[indexLOD]) {
  4846. _this._nodeSignalLODs[indexLOD].resolve();
  4847. }
  4848. }
  4849. });
  4850. this_1._loader._completePromises.push(promise);
  4851. };
  4852. var this_1 = this;
  4853. for (var indexLOD = 0; indexLOD < this._nodePromiseLODs.length; indexLOD++) {
  4854. _loop_1(indexLOD);
  4855. }
  4856. var _loop_2 = function (indexLOD) {
  4857. var promise = Promise.all(this_2._materialPromiseLODs[indexLOD]).then(function () {
  4858. if (indexLOD !== 0) {
  4859. _this._loader.endPerformanceCounter("Material LOD " + indexLOD);
  4860. }
  4861. _this._loader.log("Loaded material LOD " + indexLOD);
  4862. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  4863. if (indexLOD !== _this._materialPromiseLODs.length - 1) {
  4864. _this._loader.startPerformanceCounter("Material LOD " + (indexLOD + 1));
  4865. if (_this._materialSignalLODs[indexLOD]) {
  4866. _this._materialSignalLODs[indexLOD].resolve();
  4867. }
  4868. }
  4869. });
  4870. this_2._loader._completePromises.push(promise);
  4871. };
  4872. var this_2 = this;
  4873. for (var indexLOD = 0; indexLOD < this._materialPromiseLODs.length; indexLOD++) {
  4874. _loop_2(indexLOD);
  4875. }
  4876. };
  4877. /** @hidden */
  4878. MSFT_lod.prototype.loadNodeAsync = function (context, node, assign) {
  4879. var _this = this;
  4880. return GLTF2.GLTFLoader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  4881. var firstPromise;
  4882. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader.gltf.nodes, extension.ids);
  4883. _this._loader.logOpen("" + extensionContext);
  4884. var _loop_3 = function (indexLOD) {
  4885. var nodeLOD = nodeLODs[indexLOD];
  4886. if (indexLOD !== 0) {
  4887. _this._nodeIndexLOD = indexLOD;
  4888. _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new BABYLON.Deferred();
  4889. }
  4890. var promise = _this._loader.loadNodeAsync("#/nodes/" + nodeLOD.index, nodeLOD).then(function (babylonMesh) {
  4891. if (indexLOD !== 0) {
  4892. // TODO: should not rely on _babylonMesh
  4893. var previousNodeLOD = nodeLODs[indexLOD - 1];
  4894. if (previousNodeLOD._babylonMesh) {
  4895. previousNodeLOD._babylonMesh.dispose();
  4896. delete previousNodeLOD._babylonMesh;
  4897. _this._disposeUnusedMaterials();
  4898. }
  4899. }
  4900. return babylonMesh;
  4901. });
  4902. if (indexLOD === 0) {
  4903. firstPromise = promise;
  4904. }
  4905. else {
  4906. _this._nodeIndexLOD = null;
  4907. }
  4908. _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || [];
  4909. _this._nodePromiseLODs[indexLOD].push(promise);
  4910. };
  4911. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  4912. _loop_3(indexLOD);
  4913. }
  4914. _this._loader.logClose();
  4915. return firstPromise;
  4916. });
  4917. };
  4918. /** @hidden */
  4919. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  4920. var _this = this;
  4921. // Don't load material LODs if already loading a node LOD.
  4922. if (this._nodeIndexLOD) {
  4923. return null;
  4924. }
  4925. return GLTF2.GLTFLoader.LoadExtensionAsync(context, material, this.name, function (extensionContext, extension) {
  4926. var firstPromise;
  4927. var materialLODs = _this._getLODs(extensionContext, material, _this._loader.gltf.materials, extension.ids);
  4928. _this._loader.logOpen("" + extensionContext);
  4929. var _loop_4 = function (indexLOD) {
  4930. var materialLOD = materialLODs[indexLOD];
  4931. if (indexLOD !== 0) {
  4932. _this._materialIndexLOD = indexLOD;
  4933. }
  4934. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD.index, materialLOD, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  4935. if (indexLOD === 0) {
  4936. assign(babylonMaterial);
  4937. }
  4938. }).then(function (babylonMaterial) {
  4939. if (indexLOD !== 0) {
  4940. assign(babylonMaterial);
  4941. // TODO: should not rely on _babylonData
  4942. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  4943. if (previousBabylonDataLOD[babylonDrawMode]) {
  4944. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  4945. delete previousBabylonDataLOD[babylonDrawMode];
  4946. }
  4947. }
  4948. return babylonMaterial;
  4949. });
  4950. if (indexLOD === 0) {
  4951. firstPromise = promise;
  4952. }
  4953. else {
  4954. _this._materialIndexLOD = null;
  4955. }
  4956. _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || [];
  4957. _this._materialPromiseLODs[indexLOD].push(promise);
  4958. };
  4959. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  4960. _loop_4(indexLOD);
  4961. }
  4962. _this._loader.logClose();
  4963. return firstPromise;
  4964. });
  4965. };
  4966. /** @hidden */
  4967. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  4968. var _this = this;
  4969. // Defer the loading of uris if loading a material or node LOD.
  4970. if (this._materialIndexLOD !== null) {
  4971. this._loader.log("deferred");
  4972. var previousIndexLOD = this._materialIndexLOD - 1;
  4973. this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  4974. return this._materialSignalLODs[previousIndexLOD].promise.then(function () {
  4975. return _this._loader.loadUriAsync(context, uri);
  4976. });
  4977. }
  4978. else if (this._nodeIndexLOD !== null) {
  4979. this._loader.log("deferred");
  4980. var previousIndexLOD = this._nodeIndexLOD - 1;
  4981. this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  4982. return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () {
  4983. return _this._loader.loadUriAsync(context, uri);
  4984. });
  4985. }
  4986. return null;
  4987. };
  4988. /**
  4989. * Gets an array of LOD properties from lowest to highest.
  4990. */
  4991. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  4992. if (this.maxLODsToLoad <= 0) {
  4993. throw new Error("maxLODsToLoad must be greater than zero");
  4994. }
  4995. var properties = new Array();
  4996. for (var i = ids.length - 1; i >= 0; i--) {
  4997. properties.push(GLTF2.ArrayItem.Get(context + "/ids/" + ids[i], array, ids[i]));
  4998. if (properties.length === this.maxLODsToLoad) {
  4999. return properties;
  5000. }
  5001. }
  5002. properties.push(property);
  5003. return properties;
  5004. };
  5005. MSFT_lod.prototype._disposeUnusedMaterials = function () {
  5006. // TODO: should not rely on _babylonData
  5007. var materials = this._loader.gltf.materials;
  5008. if (materials) {
  5009. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  5010. var material = materials_1[_i];
  5011. if (material._babylonData) {
  5012. for (var drawMode in material._babylonData) {
  5013. var babylonData = material._babylonData[drawMode];
  5014. if (babylonData.meshes.length === 0) {
  5015. babylonData.material.dispose(false, true);
  5016. delete material._babylonData[drawMode];
  5017. }
  5018. }
  5019. }
  5020. }
  5021. }
  5022. };
  5023. return MSFT_lod;
  5024. }());
  5025. Extensions.MSFT_lod = MSFT_lod;
  5026. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_lod(loader); });
  5027. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  5028. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  5029. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5030. })(BABYLON || (BABYLON = {}));
  5031. //# sourceMappingURL=MSFT_lod.js.map
  5032. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  5033. var BABYLON;
  5034. (function (BABYLON) {
  5035. var GLTF2;
  5036. (function (GLTF2) {
  5037. var Loader;
  5038. (function (Loader) {
  5039. var Extensions;
  5040. (function (Extensions) {
  5041. var NAME = "MSFT_minecraftMesh";
  5042. /** @hidden */
  5043. var MSFT_minecraftMesh = /** @class */ (function () {
  5044. function MSFT_minecraftMesh(loader) {
  5045. this.name = NAME;
  5046. this.enabled = true;
  5047. this._loader = loader;
  5048. }
  5049. MSFT_minecraftMesh.prototype.dispose = function () {
  5050. delete this._loader;
  5051. };
  5052. MSFT_minecraftMesh.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  5053. var _this = this;
  5054. return GLTF2.GLTFLoader.LoadExtraAsync(context, material, this.name, function (extraContext, extra) {
  5055. if (extra) {
  5056. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  5057. throw new Error(extraContext + ": Material type not supported");
  5058. }
  5059. var promise = _this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);
  5060. if (babylonMaterial.needAlphaBlending()) {
  5061. babylonMaterial.forceDepthWrite = true;
  5062. babylonMaterial.separateCullingPass = true;
  5063. }
  5064. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  5065. babylonMaterial.twoSidedLighting = true;
  5066. return promise;
  5067. }
  5068. return null;
  5069. });
  5070. };
  5071. return MSFT_minecraftMesh;
  5072. }());
  5073. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  5074. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  5075. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  5076. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  5077. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5078. })(BABYLON || (BABYLON = {}));
  5079. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  5080. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  5081. var BABYLON;
  5082. (function (BABYLON) {
  5083. var GLTF2;
  5084. (function (GLTF2) {
  5085. var Loader;
  5086. (function (Loader) {
  5087. var Extensions;
  5088. (function (Extensions) {
  5089. var NAME = "MSFT_sRGBFactors";
  5090. /** @hidden */
  5091. var MSFT_sRGBFactors = /** @class */ (function () {
  5092. function MSFT_sRGBFactors(loader) {
  5093. this.name = NAME;
  5094. this.enabled = true;
  5095. this._loader = loader;
  5096. }
  5097. MSFT_sRGBFactors.prototype.dispose = function () {
  5098. delete this._loader;
  5099. };
  5100. MSFT_sRGBFactors.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  5101. var _this = this;
  5102. return GLTF2.GLTFLoader.LoadExtraAsync(context, material, this.name, function (extraContext, extra) {
  5103. if (extra) {
  5104. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  5105. throw new Error(extraContext + ": Material type not supported");
  5106. }
  5107. var promise = _this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);
  5108. if (!babylonMaterial.albedoTexture) {
  5109. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  5110. }
  5111. if (!babylonMaterial.reflectivityTexture) {
  5112. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  5113. }
  5114. return promise;
  5115. }
  5116. return null;
  5117. });
  5118. };
  5119. return MSFT_sRGBFactors;
  5120. }());
  5121. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  5122. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  5123. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  5124. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  5125. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5126. })(BABYLON || (BABYLON = {}));
  5127. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  5128. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  5129. var BABYLON;
  5130. (function (BABYLON) {
  5131. var GLTF2;
  5132. (function (GLTF2) {
  5133. var Loader;
  5134. (function (Loader) {
  5135. var Extensions;
  5136. (function (Extensions) {
  5137. var NAME = "MSFT_audio_emitter";
  5138. /**
  5139. * [Specification](https://github.com/najadojo/glTF/tree/MSFT_audio_emitter/extensions/2.0/Vendor/MSFT_audio_emitter)
  5140. */
  5141. var MSFT_audio_emitter = /** @class */ (function () {
  5142. /** @hidden */
  5143. function MSFT_audio_emitter(loader) {
  5144. /** The name of this extension. */
  5145. this.name = NAME;
  5146. /** Defines whether this extension is enabled. */
  5147. this.enabled = true;
  5148. this._loader = loader;
  5149. }
  5150. /** @hidden */
  5151. MSFT_audio_emitter.prototype.dispose = function () {
  5152. delete this._loader;
  5153. delete this._clips;
  5154. delete this._emitters;
  5155. };
  5156. /** @hidden */
  5157. MSFT_audio_emitter.prototype.onLoading = function () {
  5158. var extensions = this._loader.gltf.extensions;
  5159. if (extensions && extensions[this.name]) {
  5160. var extension = extensions[this.name];
  5161. this._clips = extension.clips;
  5162. this._emitters = extension.emitters;
  5163. GLTF2.ArrayItem.Assign(this._clips);
  5164. GLTF2.ArrayItem.Assign(this._emitters);
  5165. }
  5166. };
  5167. /** @hidden */
  5168. MSFT_audio_emitter.prototype.loadSceneAsync = function (context, scene) {
  5169. var _this = this;
  5170. return GLTF2.GLTFLoader.LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) {
  5171. var promises = new Array();
  5172. promises.push(_this._loader.loadSceneAsync(context, scene));
  5173. for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) {
  5174. var emitterIndex = _a[_i];
  5175. var emitter = GLTF2.ArrayItem.Get(extensionContext + "/emitters", _this._emitters, emitterIndex);
  5176. if (emitter.refDistance != undefined || emitter.maxDistance != undefined || emitter.rolloffFactor != undefined ||
  5177. emitter.distanceModel != undefined || emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  5178. throw new Error(extensionContext + ": Direction or Distance properties are not allowed on emitters attached to a scene");
  5179. }
  5180. promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter.index, emitter));
  5181. }
  5182. return Promise.all(promises).then(function () { });
  5183. });
  5184. };
  5185. /** @hidden */
  5186. MSFT_audio_emitter.prototype.loadNodeAsync = function (context, node, assign) {
  5187. var _this = this;
  5188. return GLTF2.GLTFLoader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  5189. var promises = new Array();
  5190. return _this._loader.loadNodeAsync(extensionContext, node, function (babylonMesh) {
  5191. var _loop_1 = function (emitterIndex) {
  5192. var emitter = GLTF2.ArrayItem.Get(extensionContext + "/emitters", _this._emitters, emitterIndex);
  5193. promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter.index, emitter).then(function () {
  5194. for (var _i = 0, _a = emitter._babylonSounds; _i < _a.length; _i++) {
  5195. var sound = _a[_i];
  5196. sound.attachToMesh(babylonMesh);
  5197. if (emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  5198. sound.setLocalDirectionToMesh(BABYLON.Vector3.Forward());
  5199. 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);
  5200. }
  5201. }
  5202. }));
  5203. };
  5204. for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) {
  5205. var emitterIndex = _a[_i];
  5206. _loop_1(emitterIndex);
  5207. }
  5208. assign(babylonMesh);
  5209. }).then(function (babylonMesh) {
  5210. return Promise.all(promises).then(function () {
  5211. return babylonMesh;
  5212. });
  5213. });
  5214. });
  5215. };
  5216. /** @hidden */
  5217. MSFT_audio_emitter.prototype.loadAnimationAsync = function (context, animation) {
  5218. var _this = this;
  5219. return GLTF2.GLTFLoader.LoadExtensionAsync(context, animation, this.name, function (extensionContext, extension) {
  5220. return _this._loader.loadAnimationAsync(context, animation).then(function (babylonAnimationGroup) {
  5221. var promises = new Array();
  5222. GLTF2.ArrayItem.Assign(extension.events);
  5223. for (var _i = 0, _a = extension.events; _i < _a.length; _i++) {
  5224. var event_1 = _a[_i];
  5225. promises.push(_this._loadAnimationEventAsync(extensionContext + "/events/" + event_1.index, context, animation, event_1, babylonAnimationGroup));
  5226. }
  5227. return Promise.all(promises).then(function () {
  5228. return babylonAnimationGroup;
  5229. });
  5230. });
  5231. });
  5232. };
  5233. MSFT_audio_emitter.prototype._loadClipAsync = function (context, clip) {
  5234. if (clip._objectURL) {
  5235. return clip._objectURL;
  5236. }
  5237. var promise;
  5238. if (clip.uri) {
  5239. promise = this._loader.loadUriAsync(context, clip.uri);
  5240. }
  5241. else {
  5242. var bufferView = GLTF2.ArrayItem.Get(context + "/bufferView", this._loader.gltf.bufferViews, clip.bufferView);
  5243. promise = this._loader.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView);
  5244. }
  5245. clip._objectURL = promise.then(function (data) {
  5246. return URL.createObjectURL(new Blob([data], { type: clip.mimeType }));
  5247. });
  5248. return clip._objectURL;
  5249. };
  5250. MSFT_audio_emitter.prototype._loadEmitterAsync = function (context, emitter) {
  5251. var _this = this;
  5252. emitter._babylonSounds = emitter._babylonSounds || [];
  5253. if (!emitter._babylonData) {
  5254. var clipPromises = new Array();
  5255. var name_1 = emitter.name || "emitter" + emitter.index;
  5256. var options_1 = {
  5257. loop: false,
  5258. autoplay: false,
  5259. volume: emitter.volume == undefined ? 1 : emitter.volume,
  5260. };
  5261. var _loop_2 = function (i) {
  5262. var clipContext = "#/extensions/" + this_1.name + "/clips";
  5263. var clip = GLTF2.ArrayItem.Get(clipContext, this_1._clips, emitter.clips[i].clip);
  5264. clipPromises.push(this_1._loadClipAsync(clipContext + "/" + emitter.clips[i].clip, clip).then(function (objectURL) {
  5265. var sound = emitter._babylonSounds[i] = new BABYLON.Sound(name_1, objectURL, _this._loader.babylonScene, null, options_1);
  5266. sound.refDistance = emitter.refDistance || 1;
  5267. sound.maxDistance = emitter.maxDistance || 256;
  5268. sound.rolloffFactor = emitter.rolloffFactor || 1;
  5269. sound.distanceModel = emitter.distanceModel || 'exponential';
  5270. sound._positionInEmitterSpace = true;
  5271. }));
  5272. };
  5273. var this_1 = this;
  5274. for (var i = 0; i < emitter.clips.length; i++) {
  5275. _loop_2(i);
  5276. }
  5277. var promise = Promise.all(clipPromises).then(function () {
  5278. var weights = emitter.clips.map(function (clip) { return clip.weight || 1; });
  5279. var weightedSound = new BABYLON.WeightedSound(emitter.loop || false, emitter._babylonSounds, weights);
  5280. if (emitter.innerAngle)
  5281. weightedSound.directionalConeInnerAngle = 2 * BABYLON.Tools.ToDegrees(emitter.innerAngle);
  5282. if (emitter.outerAngle)
  5283. weightedSound.directionalConeOuterAngle = 2 * BABYLON.Tools.ToDegrees(emitter.outerAngle);
  5284. if (emitter.volume)
  5285. weightedSound.volume = emitter.volume;
  5286. emitter._babylonData.sound = weightedSound;
  5287. });
  5288. emitter._babylonData = {
  5289. loaded: promise
  5290. };
  5291. }
  5292. return emitter._babylonData.loaded;
  5293. };
  5294. MSFT_audio_emitter.prototype._getEventAction = function (context, sound, action, time, startOffset) {
  5295. switch (action) {
  5296. case "play" /* play */: {
  5297. return function (currentFrame) {
  5298. var frameOffset = (startOffset || 0) + (currentFrame - time);
  5299. sound.play(frameOffset);
  5300. };
  5301. }
  5302. case "stop" /* stop */: {
  5303. return function (currentFrame) {
  5304. sound.stop();
  5305. };
  5306. }
  5307. case "pause" /* pause */: {
  5308. return function (currentFrame) {
  5309. sound.pause();
  5310. };
  5311. }
  5312. default: {
  5313. throw new Error(context + ": Unsupported action " + action);
  5314. }
  5315. }
  5316. };
  5317. MSFT_audio_emitter.prototype._loadAnimationEventAsync = function (context, animationContext, animation, event, babylonAnimationGroup) {
  5318. var _this = this;
  5319. if (babylonAnimationGroup.targetedAnimations.length == 0) {
  5320. return Promise.resolve();
  5321. }
  5322. var babylonAnimation = babylonAnimationGroup.targetedAnimations[0];
  5323. var emitterIndex = event.emitter;
  5324. var emitter = GLTF2.ArrayItem.Get("#/extensions/" + this.name + "/emitters", this._emitters, emitterIndex);
  5325. return this._loadEmitterAsync(context, emitter).then(function () {
  5326. var sound = emitter._babylonData.sound;
  5327. if (sound) {
  5328. var babylonAnimationEvent = new BABYLON.AnimationEvent(event.time, _this._getEventAction(context, sound, event.action, event.time, event.startOffset));
  5329. babylonAnimation.animation.addEvent(babylonAnimationEvent);
  5330. // Make sure all started audio stops when this animation is terminated.
  5331. babylonAnimationGroup.onAnimationGroupEndObservable.add(function () {
  5332. sound.stop();
  5333. });
  5334. babylonAnimationGroup.onAnimationGroupPauseObservable.add(function () {
  5335. sound.pause();
  5336. });
  5337. }
  5338. });
  5339. };
  5340. return MSFT_audio_emitter;
  5341. }());
  5342. Extensions.MSFT_audio_emitter = MSFT_audio_emitter;
  5343. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_audio_emitter(loader); });
  5344. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  5345. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  5346. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5347. })(BABYLON || (BABYLON = {}));
  5348. //# sourceMappingURL=MSFT_audio_emitter.js.map
  5349. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  5350. var BABYLON;
  5351. (function (BABYLON) {
  5352. var GLTF2;
  5353. (function (GLTF2) {
  5354. var Loader;
  5355. (function (Loader) {
  5356. var Extensions;
  5357. (function (Extensions) {
  5358. var NAME = "KHR_draco_mesh_compression";
  5359. /**
  5360. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  5361. */
  5362. var KHR_draco_mesh_compression = /** @class */ (function () {
  5363. /** @hidden */
  5364. function KHR_draco_mesh_compression(loader) {
  5365. /** The name of this extension. */
  5366. this.name = NAME;
  5367. /** Defines whether this extension is enabled. */
  5368. this.enabled = BABYLON.DracoCompression.DecoderAvailable;
  5369. this._loader = loader;
  5370. }
  5371. /** @hidden */
  5372. KHR_draco_mesh_compression.prototype.dispose = function () {
  5373. if (this._dracoCompression) {
  5374. this._dracoCompression.dispose();
  5375. delete this._dracoCompression;
  5376. }
  5377. delete this._loader;
  5378. };
  5379. /** @hidden */
  5380. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  5381. var _this = this;
  5382. return GLTF2.GLTFLoader.LoadExtensionAsync(context, primitive, this.name, function (extensionContext, extension) {
  5383. if (primitive.mode != undefined) {
  5384. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  5385. primitive.mode !== 4 /* TRIANGLES */) {
  5386. throw new Error(context + ": Unsupported mode " + primitive.mode);
  5387. }
  5388. // TODO: handle triangle strips
  5389. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  5390. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  5391. }
  5392. }
  5393. var attributes = {};
  5394. var loadAttribute = function (name, kind) {
  5395. var uniqueId = extension.attributes[name];
  5396. if (uniqueId == undefined) {
  5397. return;
  5398. }
  5399. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  5400. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  5401. babylonMesh._delayInfo.push(kind);
  5402. }
  5403. attributes[kind] = uniqueId;
  5404. };
  5405. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  5406. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  5407. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  5408. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  5409. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  5410. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  5411. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  5412. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  5413. var bufferView = GLTF2.ArrayItem.Get(extensionContext, _this._loader.gltf.bufferViews, extension.bufferView);
  5414. if (!bufferView._dracoBabylonGeometry) {
  5415. bufferView._dracoBabylonGeometry = _this._loader.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  5416. if (!_this._dracoCompression) {
  5417. _this._dracoCompression = new BABYLON.DracoCompression();
  5418. }
  5419. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  5420. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader.babylonScene);
  5421. babylonVertexData.applyToGeometry(babylonGeometry);
  5422. return babylonGeometry;
  5423. }).catch(function (error) {
  5424. throw new Error(context + ": " + error.message);
  5425. });
  5426. });
  5427. }
  5428. return bufferView._dracoBabylonGeometry;
  5429. });
  5430. };
  5431. return KHR_draco_mesh_compression;
  5432. }());
  5433. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  5434. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  5435. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  5436. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  5437. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5438. })(BABYLON || (BABYLON = {}));
  5439. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  5440. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  5441. var BABYLON;
  5442. (function (BABYLON) {
  5443. var GLTF2;
  5444. (function (GLTF2) {
  5445. var Loader;
  5446. (function (Loader) {
  5447. var Extensions;
  5448. (function (Extensions) {
  5449. var NAME = "KHR_materials_pbrSpecularGlossiness";
  5450. /**
  5451. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  5452. */
  5453. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function () {
  5454. /** @hidden */
  5455. function KHR_materials_pbrSpecularGlossiness(loader) {
  5456. /** The name of this extension. */
  5457. this.name = NAME;
  5458. /** Defines whether this extension is enabled. */
  5459. this.enabled = true;
  5460. this._loader = loader;
  5461. }
  5462. /** @hidden */
  5463. KHR_materials_pbrSpecularGlossiness.prototype.dispose = function () {
  5464. delete this._loader;
  5465. };
  5466. /** @hidden */
  5467. KHR_materials_pbrSpecularGlossiness.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  5468. var _this = this;
  5469. return GLTF2.GLTFLoader.LoadExtensionAsync(context, material, this.name, function (extensionContext, extension) {
  5470. var promises = new Array();
  5471. promises.push(_this._loader.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  5472. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  5473. _this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);
  5474. return Promise.all(promises).then(function () { });
  5475. });
  5476. };
  5477. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  5478. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  5479. throw new Error(context + ": Material type not supported");
  5480. }
  5481. var promises = new Array();
  5482. babylonMaterial.metallic = null;
  5483. babylonMaterial.roughness = null;
  5484. if (properties.diffuseFactor) {
  5485. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  5486. babylonMaterial.alpha = properties.diffuseFactor[3];
  5487. }
  5488. else {
  5489. babylonMaterial.albedoColor = BABYLON.Color3.White();
  5490. }
  5491. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  5492. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  5493. if (properties.diffuseTexture) {
  5494. promises.push(this._loader.loadTextureInfoAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  5495. babylonMaterial.albedoTexture = texture;
  5496. return Promise.resolve();
  5497. }));
  5498. }
  5499. if (properties.specularGlossinessTexture) {
  5500. promises.push(this._loader.loadTextureInfoAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  5501. babylonMaterial.reflectivityTexture = texture;
  5502. return Promise.resolve();
  5503. }));
  5504. babylonMaterial.reflectivityTexture.hasAlpha = true;
  5505. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  5506. }
  5507. return Promise.all(promises).then(function () { });
  5508. };
  5509. return KHR_materials_pbrSpecularGlossiness;
  5510. }());
  5511. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  5512. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  5513. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  5514. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  5515. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5516. })(BABYLON || (BABYLON = {}));
  5517. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  5518. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  5519. var BABYLON;
  5520. (function (BABYLON) {
  5521. var GLTF2;
  5522. (function (GLTF2) {
  5523. var Loader;
  5524. (function (Loader) {
  5525. var Extensions;
  5526. (function (Extensions) {
  5527. var NAME = "KHR_materials_unlit";
  5528. /**
  5529. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  5530. */
  5531. var KHR_materials_unlit = /** @class */ (function () {
  5532. /** @hidden */
  5533. function KHR_materials_unlit(loader) {
  5534. /** The name of this extension. */
  5535. this.name = NAME;
  5536. /** Defines whether this extension is enabled. */
  5537. this.enabled = true;
  5538. this._loader = loader;
  5539. }
  5540. /** @hidden */
  5541. KHR_materials_unlit.prototype.dispose = function () {
  5542. delete this._loader;
  5543. };
  5544. /** @hidden */
  5545. KHR_materials_unlit.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  5546. var _this = this;
  5547. return GLTF2.GLTFLoader.LoadExtensionAsync(context, material, this.name, function () {
  5548. return _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  5549. });
  5550. };
  5551. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  5552. if (!(babylonMaterial instanceof BABYLON.PBRMaterial)) {
  5553. throw new Error(context + ": Material type not supported");
  5554. }
  5555. var promises = new Array();
  5556. babylonMaterial.unlit = true;
  5557. var properties = material.pbrMetallicRoughness;
  5558. if (properties) {
  5559. if (properties.baseColorFactor) {
  5560. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  5561. babylonMaterial.alpha = properties.baseColorFactor[3];
  5562. }
  5563. else {
  5564. babylonMaterial.albedoColor = BABYLON.Color3.White();
  5565. }
  5566. if (properties.baseColorTexture) {
  5567. promises.push(this._loader.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  5568. babylonMaterial.albedoTexture = texture;
  5569. return Promise.resolve();
  5570. }));
  5571. }
  5572. }
  5573. if (material.doubleSided) {
  5574. babylonMaterial.backFaceCulling = false;
  5575. babylonMaterial.twoSidedLighting = true;
  5576. }
  5577. this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);
  5578. return Promise.all(promises).then(function () { });
  5579. };
  5580. return KHR_materials_unlit;
  5581. }());
  5582. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  5583. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  5584. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  5585. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  5586. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5587. })(BABYLON || (BABYLON = {}));
  5588. //# sourceMappingURL=KHR_materials_unlit.js.map
  5589. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  5590. var BABYLON;
  5591. (function (BABYLON) {
  5592. var GLTF2;
  5593. (function (GLTF2) {
  5594. var Loader;
  5595. (function (Loader) {
  5596. var Extensions;
  5597. (function (Extensions) {
  5598. var NAME = "KHR_lights_punctual";
  5599. var LightType;
  5600. (function (LightType) {
  5601. LightType["DIRECTIONAL"] = "directional";
  5602. LightType["POINT"] = "point";
  5603. LightType["SPOT"] = "spot";
  5604. })(LightType || (LightType = {}));
  5605. /**
  5606. * [Specification](https://github.com/KhronosGroup/glTF/blob/1048d162a44dbcb05aefc1874bfd423cf60135a6/extensions/2.0/Khronos/KHR_lights_punctual/README.md) (Experimental)
  5607. */
  5608. var KHR_lights = /** @class */ (function () {
  5609. /** @hidden */
  5610. function KHR_lights(loader) {
  5611. /** The name of this extension. */
  5612. this.name = NAME;
  5613. /** Defines whether this extension is enabled. */
  5614. this.enabled = true;
  5615. this._loader = loader;
  5616. }
  5617. /** @hidden */
  5618. KHR_lights.prototype.dispose = function () {
  5619. delete this._loader;
  5620. delete this._lights;
  5621. };
  5622. /** @hidden */
  5623. KHR_lights.prototype.onLoading = function () {
  5624. var extensions = this._loader.gltf.extensions;
  5625. if (extensions && extensions[this.name]) {
  5626. var extension = extensions[this.name];
  5627. this._lights = extension.lights;
  5628. }
  5629. };
  5630. /** @hidden */
  5631. KHR_lights.prototype.loadNodeAsync = function (context, node, assign) {
  5632. var _this = this;
  5633. return GLTF2.GLTFLoader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  5634. return _this._loader.loadNodeAsync(context, node, function (babylonMesh) {
  5635. var babylonLight;
  5636. var light = GLTF2.ArrayItem.Get(extensionContext, _this._lights, extension.light);
  5637. var name = light.name || babylonMesh.name;
  5638. switch (light.type) {
  5639. case LightType.DIRECTIONAL: {
  5640. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Backward(), _this._loader.babylonScene);
  5641. break;
  5642. }
  5643. case LightType.POINT: {
  5644. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader.babylonScene);
  5645. break;
  5646. }
  5647. case LightType.SPOT: {
  5648. var babylonSpotLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Backward(), 0, 1, _this._loader.babylonScene);
  5649. babylonSpotLight.angle = ((light.spot && light.spot.outerConeAngle) || Math.PI / 4) * 2;
  5650. babylonSpotLight.innerAngle = ((light.spot && light.spot.innerConeAngle) || 0) * 2;
  5651. babylonLight = babylonSpotLight;
  5652. break;
  5653. }
  5654. default: {
  5655. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  5656. }
  5657. }
  5658. babylonLight.falloffType = BABYLON.Light.FALLOFF_GLTF;
  5659. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  5660. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  5661. babylonLight.range = light.range == undefined ? Number.MAX_VALUE : light.range;
  5662. babylonLight.parent = babylonMesh;
  5663. assign(babylonMesh);
  5664. });
  5665. });
  5666. };
  5667. return KHR_lights;
  5668. }());
  5669. Extensions.KHR_lights = KHR_lights;
  5670. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_lights(loader); });
  5671. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  5672. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  5673. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5674. })(BABYLON || (BABYLON = {}));
  5675. //# sourceMappingURL=KHR_lights_punctual.js.map
  5676. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  5677. var BABYLON;
  5678. (function (BABYLON) {
  5679. var GLTF2;
  5680. (function (GLTF2) {
  5681. var Loader;
  5682. (function (Loader) {
  5683. var Extensions;
  5684. (function (Extensions) {
  5685. var NAME = "KHR_texture_transform";
  5686. /**
  5687. * [Specification](https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_texture_transform/README.md)
  5688. */
  5689. var KHR_texture_transform = /** @class */ (function () {
  5690. /** @hidden */
  5691. function KHR_texture_transform(loader) {
  5692. /** The name of this extension. */
  5693. this.name = NAME;
  5694. /** Defines whether this extension is enabled. */
  5695. this.enabled = true;
  5696. this._loader = loader;
  5697. }
  5698. /** @hidden */
  5699. KHR_texture_transform.prototype.dispose = function () {
  5700. delete this._loader;
  5701. };
  5702. /** @hidden */
  5703. KHR_texture_transform.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) {
  5704. var _this = this;
  5705. return GLTF2.GLTFLoader.LoadExtensionAsync(context, textureInfo, this.name, function (extensionContext, extension) {
  5706. return _this._loader.loadTextureInfoAsync(context, textureInfo, function (babylonTexture) {
  5707. if (!(babylonTexture instanceof BABYLON.Texture)) {
  5708. throw new Error(extensionContext + ": Texture type not supported");
  5709. }
  5710. if (extension.offset) {
  5711. babylonTexture.uOffset = extension.offset[0];
  5712. babylonTexture.vOffset = extension.offset[1];
  5713. }
  5714. // Always rotate around the origin.
  5715. babylonTexture.uRotationCenter = 0;
  5716. babylonTexture.vRotationCenter = 0;
  5717. if (extension.rotation) {
  5718. babylonTexture.wAng = -extension.rotation;
  5719. }
  5720. if (extension.scale) {
  5721. babylonTexture.uScale = extension.scale[0];
  5722. babylonTexture.vScale = extension.scale[1];
  5723. }
  5724. if (extension.texCoord != undefined) {
  5725. babylonTexture.coordinatesIndex = extension.texCoord;
  5726. }
  5727. assign(babylonTexture);
  5728. });
  5729. });
  5730. };
  5731. return KHR_texture_transform;
  5732. }());
  5733. Extensions.KHR_texture_transform = KHR_texture_transform;
  5734. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_texture_transform(loader); });
  5735. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  5736. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  5737. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5738. })(BABYLON || (BABYLON = {}));
  5739. //# sourceMappingURL=KHR_texture_transform.js.map
  5740. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  5741. var BABYLON;
  5742. (function (BABYLON) {
  5743. var GLTF2;
  5744. (function (GLTF2) {
  5745. var Loader;
  5746. (function (Loader) {
  5747. var Extensions;
  5748. (function (Extensions) {
  5749. var NAME = "EXT_lights_image_based";
  5750. /**
  5751. * [Specification](https://github.com/KhronosGroup/glTF/blob/eb3e32332042e04691a5f35103f8c261e50d8f1e/extensions/2.0/Khronos/EXT_lights_image_based/README.md) (Experimental)
  5752. */
  5753. var EXT_lights_image_based = /** @class */ (function () {
  5754. /** @hidden */
  5755. function EXT_lights_image_based(loader) {
  5756. /** The name of this extension. */
  5757. this.name = NAME;
  5758. /** Defines whether this extension is enabled. */
  5759. this.enabled = true;
  5760. this._loader = loader;
  5761. }
  5762. /** @hidden */
  5763. EXT_lights_image_based.prototype.dispose = function () {
  5764. delete this._loader;
  5765. delete this._lights;
  5766. };
  5767. /** @hidden */
  5768. EXT_lights_image_based.prototype.onLoading = function () {
  5769. var extensions = this._loader.gltf.extensions;
  5770. if (extensions && extensions[this.name]) {
  5771. var extension = extensions[this.name];
  5772. this._lights = extension.lights;
  5773. }
  5774. };
  5775. /** @hidden */
  5776. EXT_lights_image_based.prototype.loadSceneAsync = function (context, scene) {
  5777. var _this = this;
  5778. return GLTF2.GLTFLoader.LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) {
  5779. var promises = new Array();
  5780. promises.push(_this._loader.loadSceneAsync(context, scene));
  5781. _this._loader.logOpen("" + extensionContext);
  5782. var light = GLTF2.ArrayItem.Get(extensionContext + "/light", _this._lights, extension.light);
  5783. promises.push(_this._loadLightAsync("#/extensions/" + _this.name + "/lights/" + extension.light, light).then(function (texture) {
  5784. _this._loader.babylonScene.environmentTexture = texture;
  5785. }));
  5786. _this._loader.logClose();
  5787. return Promise.all(promises).then(function () { });
  5788. });
  5789. };
  5790. EXT_lights_image_based.prototype._loadLightAsync = function (context, light) {
  5791. var _this = this;
  5792. if (!light._loaded) {
  5793. var promises = new Array();
  5794. this._loader.logOpen("" + context);
  5795. var imageData_1 = new Array(light.specularImages.length);
  5796. var _loop_1 = function (mipmap) {
  5797. var faces = light.specularImages[mipmap];
  5798. imageData_1[mipmap] = new Array(faces.length);
  5799. var _loop_2 = function (face) {
  5800. var specularImageContext = context + "/specularImages/" + mipmap + "/" + face;
  5801. this_1._loader.logOpen("" + specularImageContext);
  5802. var index = faces[face];
  5803. var image = GLTF2.ArrayItem.Get(specularImageContext, this_1._loader.gltf.images, index);
  5804. promises.push(this_1._loader.loadImageAsync("#/images/" + index, image).then(function (data) {
  5805. imageData_1[mipmap][face] = data;
  5806. }));
  5807. this_1._loader.logClose();
  5808. };
  5809. for (var face = 0; face < faces.length; face++) {
  5810. _loop_2(face);
  5811. }
  5812. };
  5813. var this_1 = this;
  5814. for (var mipmap = 0; mipmap < light.specularImages.length; mipmap++) {
  5815. _loop_1(mipmap);
  5816. }
  5817. this._loader.logClose();
  5818. light._loaded = Promise.all(promises).then(function () {
  5819. var babylonTexture = new BABYLON.RawCubeTexture(_this._loader.babylonScene, null, light.specularImageSize);
  5820. light._babylonTexture = babylonTexture;
  5821. if (light.intensity != undefined) {
  5822. babylonTexture.level = light.intensity;
  5823. }
  5824. if (light.rotation) {
  5825. var rotation = BABYLON.Quaternion.FromArray(light.rotation);
  5826. // Invert the rotation so that positive rotation is counter-clockwise.
  5827. if (!_this._loader.babylonScene.useRightHandedSystem) {
  5828. rotation = BABYLON.Quaternion.Inverse(rotation);
  5829. }
  5830. BABYLON.Matrix.FromQuaternionToRef(rotation, babylonTexture.getReflectionTextureMatrix());
  5831. }
  5832. var sphericalHarmonics = BABYLON.SphericalHarmonics.FromArray(light.irradianceCoefficients);
  5833. sphericalHarmonics.scale(light.intensity);
  5834. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  5835. var sphericalPolynomial = BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  5836. // Compute the lod generation scale to fit exactly to the number of levels available.
  5837. var lodGenerationScale = (imageData_1.length - 1) / BABYLON.Scalar.Log2(light.specularImageSize);
  5838. return babylonTexture.updateRGBDAsync(imageData_1, sphericalPolynomial, lodGenerationScale);
  5839. });
  5840. }
  5841. return light._loaded.then(function () {
  5842. return light._babylonTexture;
  5843. });
  5844. };
  5845. return EXT_lights_image_based;
  5846. }());
  5847. Extensions.EXT_lights_image_based = EXT_lights_image_based;
  5848. GLTF2.GLTFLoader.RegisterExtension(NAME, function (loader) { return new EXT_lights_image_based(loader); });
  5849. })(Extensions = Loader.Extensions || (Loader.Extensions = {}));
  5850. })(Loader = GLTF2.Loader || (GLTF2.Loader = {}));
  5851. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  5852. })(BABYLON || (BABYLON = {}));
  5853. //# sourceMappingURL=EXT_lights_image_based.js.map